-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLongestPalindrome.php
More file actions
44 lines (38 loc) · 983 Bytes
/
LongestPalindrome.php
File metadata and controls
44 lines (38 loc) · 983 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
declare(strict_types=1);
namespace leetcode;
class LongestPalindrome
{
public static function longestPalindrome(string $s): int
{
if (empty($s)) {
return 0;
}
[$ans, $map] = [0, []];
for ($i = 0, $n = strlen($s); $i < $n; $i++) {
$map[$s[$i]] = ($map[$s[$i]] ?? 0) + 1;
if ($map[$s[$i]] === 2) {
$ans += 2;
unset($map[$s[$i]]);
}
}
return $map ? $ans + 1 : $ans;
}
public static function longestPalindrome2(string $s): int
{
if (empty($s)) {
return 0;
}
[$ans, $n] = [0, strlen($s)];
for ($i = 0; $i < $n; $i++) {
$map[$s[$i]] = ($map[$s[$i]] ?? 0) + 1;
}
foreach ($map as $val) {
$ans += (int)($val / 2) * 2;
if ($ans % 2 === 0 && $val % 2 === 1) {
$ans++;
}
}
return $ans;
}
}