-
Notifications
You must be signed in to change notification settings - Fork 17
/
longest-palindromic-substring.py
41 lines (32 loc) · 1.39 KB
/
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
from collections import deque
class Solution:
def check_palindrome(self, s, left_pointer, right_pointer):
result = ""
while right_pointer < len(s) and left_pointer >= 0:
if s[left_pointer] == s[right_pointer]:
palindrome = s[left_pointer:(right_pointer + 1)]
result = palindrome if len(palindrome) > len(result) else result
left_pointer -= 1
right_pointer += 1
else:
break
return result
def longestPalindrome(self, s):
result = ""
for position in range(len(s)):
palindrome_type1 = self.check_palindrome(s, position, position)
result = palindrome_type1 \
if len(palindrome_type1) > len(result) else result
palindrome_type2 = self.check_palindrome(s, position - 1, position)
result = palindrome_type2 \
if len(palindrome_type2) > len(result) else result
return result
s = Solution()
assert s.longestPalindrome("cbbd") == "bb"
assert s.longestPalindrome("babad") == "bab" or s.longestPalindrome("babad") == "aba"
assert s.longestPalindrome("bbccbbbbbabbbbb") == "bbbbbabbbbb"
assert s.longestPalindrome("") == ""
assert s.longestPalindrome("a") == "a"
assert s.longestPalindrome("ac") == "a"
assert s.longestPalindrome("ccc") == "ccc"
assert s.longestPalindrome("cccc") == "cccc"