-
Notifications
You must be signed in to change notification settings - Fork 0
/
longestPlindrome.py
75 lines (56 loc) · 1.48 KB
/
longestPlindrome.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
# Given a string s, return the longest
# palindromic
# substring
# in s.
# Example 1:
# Input: s = "babad"
# Output: "bab"
# Explanation: "aba" is also a valid answer.
# Example 2:
# Input: s = "cbbd"
# Output: "bb"
# Constraints:
# 1 <= s.length <= 1000
# s consist of only digits and English letters.
def checkPalindrome(s):
if s == '':
return False
n = len(s)
i = 0
while i <= n//2:
if s[i] != s[n-1-i]:
return False
i+=1
return True
def longestPalindromeV1(s):
size = len(s)
max_lenght = 0
for i in range(size):
for j in range(i+1, size):
print("calculating palindome for s ", i, j, s[i:j])
is_palindrome = checkPalindrome(s[i:j])
if is_palindrome:
max_lenght = max(max_lenght, j-i + 1)
# print(s[i])
return max_lenght
def get_palindrome_leght(s, mid_index):
n = len(s)
i = 1
# Check all left and right
while mid_index-i >=0 and mid_index+i <=n-1 and s[mid_index-i] == s[mid_index+i]:
i += 1
return 1 + 2*(i-1)
def longestPalindrome(s):
size = len(s)
max_lenght = 0
for i in range(size):
# Check odd lenght palindrome
length = get_palindrome_leght(s,i)
max_lenght = max(max_lenght, length)
# TODO even length palindrome
return max_lenght
s = "acbabcf"
s = "abcdcb"
# longestPalindrome(s)
ans = longestPalindromeV1(s)
print(ans)