-
Notifications
You must be signed in to change notification settings - Fork 0
/
5_LongestPalindromicSubstring.py
87 lines (66 loc) · 2.04 KB
/
5_LongestPalindromicSubstring.py
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# ----------------------------------
# Question Description
# ----------------------------------
'''
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
------------------------------------
Examples:
Example 1:
---
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example:
---
Input: "cbbd"
Output: "bb"
***
Manacher's Algorithm
http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html
'''
# ----------------------------------
# Instruction
# ----------------------------------
class Solution:
def preProcess(self, s):
"""
Transform s into T
For example, s = 'abba', T = '^#a#b#a#a#$'
^ and $ signs are sentinels appended to each end to avoid bounds checking.
"""
if len(s) == 0:
return '^$'
ret = '^'
for i in s:
ret += '#%s' % i
ret += '#$'
return ret
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
T = self.preProcess(s)
n = len(T)
P = [0] * n
Center, Right = 0, 0
for i in range(1, n - 1):
i_mirror = 2 * Center - i # equals to i' = C - (i - C)
P[i] = min(Right - i, P[i_mirror]) if (Right > i) else 0
# Attemp to expand palindrome centered at i
while (T[i + 1 + P[i]] == T[i - 1 - P[i]]):
P[i] += 1
# If palindrom centered at i expand past R,
# adjust center based on expanded palindrome.
if (i + P[i] > Right):
Center = i
Right = i + P[i]
# Find the maximum element in P
maxLen = 0
centerIndex = 0
for i in range(1, n - 1):
if P[i] > P[centerIndex]:
maxLen = P[i]
centerIndex = i
start = (centerIndex - 1 - maxLen) // 2
return s[start: start + maxLen]