-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLC5-Longest-Palindromic-Substring.py
98 lines (83 loc) · 2.63 KB
/
LC5-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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
"""
Given a string s, return the longest palindromic substring in s.
Example 1:
Input: s = "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd"
Output: "bb"
Example 3:
Input: s = "a"
Output: "a"
Example 4:
Input: s = "ac"
Output: "a"
Constraints:
1 <= s.length <= 1000
s consist of only digits and English letters (lower-case and/or upper-case),
"""
from run_tests import run_tests_belongs
class Solution:
def longestPalindrome(self, s: str) -> str:
"""
Find the longest palindrome by increasing the potential length of poly
:param s:
:return: the longest palindrome in string s
Runtime complexity: O(n^2)
Space complexity: O(n)
"""
if not s:
return 0
# max odd length
# one letter words
centers = list(range(len(s)))
# length of paly 2l + 1
for l in range(1, len(s) // 2 + 2):
new_centers = list()
for center in centers:
if center + l < len(s) and center - l >= 0 and s[center + l] == s[center - l]:
new_centers.append(center)
if not new_centers:
break
else:
centers = list(new_centers)
max_odd_length = 2 * l - 1
max_odd_paly = s[centers[0] - l + 1:centers[0] + l]
# two letter words
centers = list()
for start in range(len(s) - 1):
if s[start] == s[start + 1]:
centers.append(start)
if not centers:
return max_odd_paly
# length of paly 2l
for l in range(2, len(s) // 2 + 2):
new_centers = list()
for center in centers:
if center + l < len(s) and center + 1 - l >= 0 and s[center + l] == s[center + 1 - l]:
new_centers.append(center)
if not new_centers:
break
else:
centers = list(new_centers)
max_even_length = 2 * l - 2
max_even_paly = s[centers[0] - l + 2:centers[0] + l]
if max_even_length > max_odd_length:
return max_even_paly
else:
return max_odd_paly
if __name__ == "__main__":
correct_answers = [
["babad", set(["bab", "aba"])],
["ab", set(["a", "b"])],
["bb", set(["bb"])],
["cbbd", set(["bb"])],
["a", set(["a"])],
["babadab", set(["badab"])],
["babadda", set(["adda"])]
]
methods = ['longestPalindrome']
for method in methods:
print(f'Running tests for {method}')
run_tests_belongs(getattr(Solution(), method), correct_answers)