Skip to content

Commit 7f57ece

Browse files
committed
回文串的马拉车算法
1 parent b60d855 commit 7f57ece

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

5. 最长回文子串/file_code3.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class Solution:
2+
# 马拉车算法
3+
def longestPalindrome(self, s: str) -> str:
4+
T = preprocess(s)
5+
n = len(T)
6+
C, R = 0, 0
7+
P = [0] * n
8+
9+
for i in range(1, n-1):
10+
i_mirror = 2 * C - i
11+
P[i] = min(R-i, P[i_mirror]) if R > i else 0
12+
13+
while T[i-1-P[i]] == T[i+1+P[i]]:
14+
P[i] += 1
15+
16+
if i + P[i] > R:
17+
C = i
18+
R = P[i] + i
19+
20+
maxlen = 0
21+
center_index = 0
22+
for i in range(1, n-1):
23+
if P[i] > maxlen:
24+
maxlen = P[i]
25+
center_index = i
26+
27+
start_index = (center_index - maxlen) // 2
28+
return s[start_index: maxlen + start_index]
29+
30+
31+
def preprocess(s: str):
32+
temp_str = ''
33+
for i in s:
34+
temp_str += '#' + i
35+
36+
temp_str = '^' + temp_str + '#$'
37+
return temp_str
38+
39+
if __name__ == "__main__":
40+
solution = Solution()
41+
# string = 'cbbd'
42+
string = 'babad'
43+
44+
result = solution.longestPalindrome(string)
45+
46+
print(result)

0 commit comments

Comments
 (0)