imajinyun /
leetcode-php
| 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
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
|
|||
| 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 |