ValidAnagram   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 11
eloc 27
c 2
b 0
f 0
dl 0
loc 45
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B isAnagram2() 0 24 7
A isAnagram() 0 17 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class ValidAnagram
8
{
9
    public static function isAnagram(string $s, string $t): bool
10
    {
11
        [$m, $n] = [strlen($s), strlen($t)];
12
        if ($m !== $n) {
13
            return false;
14
        }
15
        $source = $target = [];
16
        for ($i = 0; $i < $m; $i++) {
17
            $source[] = $s[$i];
18
        }
19
        for ($i = 0; $i < $n; $i++) {
20
            $target[] = $t[$i];
21
        }
22
        sort($source);
23
        sort($target);
24
25
        return $source === $target;
26
    }
27
28
    public static function isAnagram2(string $s, string $t): bool
29
    {
30
        [$m, $n] = [strlen($s), strlen($t)];
31
        if ($m !== $n) {
32
            return false;
33
        }
34
        $map = array_fill(0, 26, 0);
35
        for ($i = 0; $i < $m; $i++) {
36
            $key = ord($s[$i]) - ord('a');
37
            if (isset($map[$key])) {
38
                $map[$key]++;
39
            }
40
        }
41
        for ($i = 0; $i < $n; $i++) {
42
            $key = ord($t[$i]) - ord('a');
43
            if (isset($map[$key])) {
44
                $map[$key]--;
45
            }
46
            if ($map[$key] < 0) {
47
                return false;
48
            }
49
        }
50
51
        return true;
52
    }
53
}
54