Skip to content

Commit d9d3017

Browse files
committed
longest palindrome substring
1 parent fcf30cc commit d9d3017

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

longestPalindrome.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# @return a string
2+
# DP approach, O(n^2)
3+
def longestPalindrome(s):
4+
l = len(s)
5+
maxStr = s[0]
6+
maxLen = 1
7+
8+
p = [[0 for i in range(l)] for j in range(l)]
9+
for i in range(l - 1):
10+
p[i][i] = 1
11+
if s[i] == s[i + 1]:
12+
if maxLen < 2:
13+
maxLen = 2
14+
maxStr = s[i:(i + 2)]
15+
p[i][i + 1] = 1
16+
else:
17+
p[i][i + 1] = 0
18+
19+
for k in range(2, l):
20+
for i in range(0, l - k):
21+
j = i + k
22+
if p[i + 1][j - 1] and s[i] == s[j]:
23+
p[i][j] = 1
24+
if maxLen < (j - i + 1):
25+
maxLen = j - i + 1
26+
maxStr = s[i:(j + 1)]
27+
else:
28+
p[i][j] = 0
29+
30+
return maxStr
31+
32+
# O(n)
33+
def longestPalindromeSubstring(s):
34+
def preProcess(s):
35+
if len(s) == 0:
36+
return ''
37+
ret = '^'
38+
for c in s:
39+
ret += '#' + c
40+
return ret + '#$'
41+
42+
T = preProcess(s)
43+
n = len(T)
44+
C = 0
45+
R = 0
46+
P = [0 for i in range(n)]
47+
for i in range(1, n - 1):
48+
iMirror = C - (i - C)
49+
P[i] = max(min(R - i, P[iMirror]), 0)
50+
51+
while T[i - P[i] - 1] == T[i + P[i] + 1]:
52+
P[i] += 1
53+
54+
if P[i] + i > R:
55+
R = P[i] + i
56+
C = i
57+
58+
maxLen = 0
59+
centerIndex = 0
60+
for i in range(1, n - 1):
61+
if P[i] > maxLen:
62+
maxLen = P[i]
63+
centerIndex = i
64+
65+
start = (centerIndex - 1 - maxLen) / 2
66+
return s[start:(start + maxLen)];
67+
68+
assert longestPalindromeSubstring('helloworld') == 'owo'
69+
assert longestPalindromeSubstring('abbc') == 'bb'
70+
assert longestPalindromeSubstring('spring') == 's'

0 commit comments

Comments
 (0)