FindCommonCharacters::commonChars()   B
last analyzed

Complexity

Conditions 7
Paths 16

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 14
c 2
b 0
f 0
dl 0
loc 23
rs 8.8333
cc 7
nc 16
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class FindCommonCharacters
8
{
9
    public static function commonChars(array $arr): array
10
    {
11
        if (empty($arr)) {
12
            return [];
13
        }
14
        [$start, $cnt, $end] = [97, 26, 122];
15
        [$ans, $map] = [[], array_fill($start, $cnt, PHP_INT_MAX)];
16
        foreach ($arr as $str) {
17
            $tmp = array_fill($start, $cnt, 0);
18
            for ($i = 0, $n = strlen($str); $i < $n; $i++) {
19
                $tmp[ord($str[$i])]++;
20
            }
21
            for ($i = $start; $i <= $end; $i++) {
22
                $map[$i] = min($map[$i], $tmp[$i]);
23
            }
24
        }
25
        for ($i = $start; $i <= $end; $i++) {
26
            while ($map[$i]-- > 0) {
27
                $ans[] = chr($i);
28
            }
29
        }
30
31
        return $ans;
32
    }
33
}
34