Test Failed
Push — master ( cc11a0...6d15a1 )
by Jinyun
10:24 queued 16s
created

LongestPalindrome::longestPalindrome()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 15
rs 9.6111
cc 5
nc 7
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class LongestPalindrome
8
{
9
    public static function longestPalindrome(string $s): int
10
    {
11
        if (empty($s)) {
12
            return 0;
13
        }
14
        [$ans, $map] = [0, []];
15
        for ($i = 0, $n = strlen($s); $i < $n; $i++) {
16
            $map[$s[$i]] = ($map[$s[$i]] ?? 0) + 1;
17
            if ($map[$s[$i]] === 2) {
18
                $ans += 2;
19
                unset($map[$s[$i]]);
20
            }
21
        }
22
23
        return $map ? $ans + 1 : $ans;
0 ignored issues
show
introduced by
$map is of type array, thus it always evaluated to false.
Loading history...
24
    }
25
26
    public static function longestPalindrome2(string $s): int
27
    {
28
        if (empty($s)) {
29
            return 0;
30
        }
31
        [$ans, $n] = [0, strlen($s)];
32
        for ($i = 0; $i < $n; $i++) {
33
            $map[$s[$i]] = ($map[$s[$i]] ?? 0) + 1;
34
        }
35
        foreach ($map as $val) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $map does not seem to be defined for all execution paths leading up to this point.
Loading history...
36
            $ans += (int)($val / 2) * 2;
37
            if ($ans % 2 === 0 && $val % 2 === 1) {
38
                $ans++;
39
            }
40
        }
41
42
        return $ans;
43
    }
44
}
45