FindWordsThatCanBeFormedByCharacters   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 16
c 1
b 0
f 0
dl 0
loc 27
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B countCharacters() 0 25 8
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class FindWordsThatCanBeFormedByCharacters
8
{
9
    public static function countCharacters(array $words, string $chars): int
10
    {
11
        if (empty($words) || empty($chars)) {
12
            return 0;
13
        }
14
        [$cnt, $map] = [0, array_fill(0, 26, 0)];
15
        for ($i = 0, $n = strlen($chars); $i < $n; $i++) {
16
            $map[ord($chars[$i]) - ord('a')]++;
17
        }
18
        foreach ($words as $word) {
19
            [$len, $see] = [0, $map];
20
            for ($i = 0, $n = strlen($word); $i < $n; $i++) {
21
                $j = ord($word[$i]) - ord('a');
22
                if ($see[$j] > 0) {
23
                    $see[$j]--;
24
                    $len++;
25
                }
26
            }
27
28
            if ($len === strlen($word)) {
29
                $cnt += $len;
30
            }
31
        }
32
33
        return $cnt;
34
    }
35
}
36