|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace leetcode; |
|
6
|
|
|
|
|
7
|
|
|
class LongestPalindromicSubstring |
|
8
|
|
|
{ |
|
9
|
|
|
public static function longestPalindrome(string $s): string |
|
10
|
|
|
{ |
|
11
|
|
|
$n = strlen($s); |
|
12
|
|
|
if ($n < 2) { |
|
13
|
|
|
return $s; |
|
14
|
|
|
} |
|
15
|
|
|
$helper = static function (string $s) { |
|
16
|
|
|
$n = strlen($s); |
|
17
|
|
|
for ($i = 0; $i < $n / 2; $i++) { |
|
18
|
|
|
if ($s[$i] !== $s[$n - $i - 1]) { |
|
19
|
|
|
return false; |
|
20
|
|
|
} |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
return true; |
|
24
|
|
|
}; |
|
25
|
|
|
[$ans, $max] = ['', 0]; |
|
26
|
|
|
for ($i = 0; $i < $n; $i++) { |
|
27
|
|
|
for ($j = 1; $j <= $n; $j++) { |
|
28
|
|
|
$tmp = substr($s, $i, $j); |
|
29
|
|
|
if ($helper($tmp) && strlen($tmp) > $max) { |
|
30
|
|
|
$ans = substr($s, $i, $j); |
|
31
|
|
|
$max = max($max, strlen($ans)); |
|
32
|
|
|
} |
|
33
|
|
|
} |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
return $ans; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
public static function longestPalindrome2(string $s): string |
|
40
|
|
|
{ |
|
41
|
|
|
$n = strlen($s); |
|
42
|
|
|
if ($n < 2) { |
|
43
|
|
|
return $s; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
$start = $length = 0; |
|
47
|
|
|
$helper = static function (string $s, int $l, int $r, int &$start, int &$length) { |
|
48
|
|
|
while ($l >= 0 && $r < strlen($s) && $s[$l ] === $s[$r]) { |
|
49
|
|
|
$l--; |
|
50
|
|
|
$r++; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
if ($length < $r - $l - 1) { |
|
54
|
|
|
$start = $l + 1; |
|
55
|
|
|
$length = $r - $l - 1; |
|
56
|
|
|
} |
|
57
|
|
|
}; |
|
58
|
|
|
for ($i = 0; $i < $n; $i++) { |
|
59
|
|
|
$helper($s, $i, $i, $start, $length); |
|
60
|
|
|
$helper($s, $i, $i + 1, $start, $length); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
return substr($s, $start, $length); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
public static function longestPalindrome3(string $s): string |
|
67
|
|
|
{ |
|
68
|
|
|
$n = strlen($s); |
|
69
|
|
|
if ($n < 2) { |
|
70
|
|
|
return $s; |
|
71
|
|
|
} |
|
72
|
|
|
[$origin, $reverse, $max, $len] = [$s, strrev($s), 0, 0]; |
|
73
|
|
|
$dp = array_fill(0, $n, array_fill(0, $n, 0)); |
|
74
|
|
|
for ($i = 0; $i < $n; $i++) { |
|
75
|
|
|
for ($j = 0; $j < $n; $j++) { |
|
76
|
|
|
if ($origin[$i] === $reverse[$j]) { |
|
77
|
|
|
if ($i === 0 || $j === 0) { |
|
78
|
|
|
$dp[$i][$j] = 1; |
|
79
|
|
|
} else { |
|
80
|
|
|
$dp[$i][$j] = $dp[$i - 1][$j - 1] + 1; |
|
81
|
|
|
} |
|
82
|
|
|
} |
|
83
|
|
|
|
|
84
|
|
|
if ($dp[$i][$j] > $max) { |
|
85
|
|
|
$prev = $n - 1 - $j; |
|
86
|
|
|
if ($prev + $dp[$i][$j] - 1 === $i) { |
|
87
|
|
|
$max = $dp[$i][$j]; |
|
88
|
|
|
$len= $i; |
|
89
|
|
|
} |
|
90
|
|
|
} |
|
91
|
|
|
} |
|
92
|
|
|
} |
|
93
|
|
|
|
|
94
|
|
|
return substr($s, $len - $max + 1, $max); |
|
95
|
|
|
} |
|
96
|
|
|
} |
|
97
|
|
|
|