Skip to content

Commit dfc02bc

Browse files
committed
Enhancement for gavinfish#1
1 parent 7b38a2b commit dfc02bc

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

python/005 Longest Palindromic Substring.py

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@
22
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
33
'''
44

5+
56
class Solution(object):
6-
def longestPalindrome(self, s):
7+
def longestPalindrome2(self, s):
78
"""
89
:type s: str
910
:rtype: str
@@ -21,7 +22,8 @@ def longestPalindrome(self, s):
2122
m = 0
2223
# Length of the current substring
2324
c = 0
24-
# Whether the substring contains the first character or last character and is palindromic
25+
# Whether the substring contains the first character or last character
26+
# and is palindromic
2527
b = True
2628
for i in range(0, n):
2729
# Odd situation
@@ -50,6 +52,26 @@ def longestPalindrome(self, s):
5052
b = True
5153
return s[l:r]
5254

55+
def longestPalindrome(self, s):
56+
string = "#" + "#".join(s) + "#"
57+
i = 0
58+
maxBorder = 0 # store the max border that has been reached
59+
maxCenter = 0 # the center of palindrome that has been largest for now
60+
p = [0 for _ in range(len(string))] # min in (center to i or i to border)
61+
res = [0, 0]
62+
63+
while i < len(string):
64+
p[i] = min(p[2 * maxCenter - i], maxBorder - i) if maxBorder > i else 1
65+
while i - p[i] >= 0 and i + p[i] < len(string) and string[i - p[i]] == string[i + p[i]]:
66+
p[i] += 1
67+
if maxBorder < p[i] + i:
68+
maxBorder = p[i] + i
69+
maxCenter = i
70+
if maxBorder - maxCenter > res[1] - res[0]:
71+
res = [maxCenter, maxBorder]
72+
i += 1
73+
74+
return "".join([x for x in string[2 * res[0] - res[1] + 1:res[1]] if x != '#'])
5375

5476

5577
if __name__ == "__main__":

0 commit comments

Comments
 (0)