-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5.longest-palindromic-substring.py
63 lines (56 loc) · 1.82 KB
/
5.longest-palindromic-substring.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
class Solution:
def longestPalindrome(self, s: str) -> str:
# if len(s)==0:
# return 0
# maxLen=1
# start=0
# for i in range(len(s)):
# if i-maxLen >=1 and s[i-maxLen-1:i+1]==s[i-maxLen-1:i+1][::-1]:
# start=i-maxLen-1
# maxLen+=2
# continue
# if s[i-maxLen:i+1]==s[i-maxLen:i+1][::-1]:
# start=i-maxLen
# maxLen+=1
# return s[start:start+maxLen]
# if len(s)==0:
# return ""
# maxLen=1
# start=0
# for i in range(len(s)):
# if i-maxLen >=1 and s[i-maxLen-1:i+1]==s[i-maxLen-1:i+1][::-1]:
# start=i-maxLen-1
# maxLen+=2
# continue
# if s[i-maxLen:i+1]==s[i-maxLen:i+1][::-1]:
# start=i-maxLen
# maxLen+=1
# return s[start:start+maxLen]
def expandAroundCenter(s, left, right):
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return s[left + 1:right]
longest = ""
for i in range(len(s)):
# Odd length palindrome
temp = expandAroundCenter(s, i, i)
if len(temp) > len(longest):
longest = temp
# Even length palindrome
temp = expandAroundCenter(s, i, i + 1)
if len(temp) > len(longest):
longest = temp
return longest
if __name__ == "__main__":
sol = Solution()
s = "babad"
print(sol.longestPalindrome(s))
s = "cbbd"
print(sol.longestPalindrome(s))
s = "a"
print(sol.longestPalindrome(s))
s = "ac"
print(sol.longestPalindrome(s))
s = "bb"
print(sol.longestPalindrome(s))