- Notifications
You must be signed in to change notification settings - Fork 363
Expand file tree
/
Copy pathManachers_Algorithm.py
More file actions
Latest commit
49 lines (34 loc) · 1.22 KB
/
Copy pathManachers_Algorithm.py
File metadata and controls
49 lines (34 loc) · 1.22 KB
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
SIZE=100000+1
P= [0] * (SIZE*2)
# Transform S into new string Q with special characters inserted to avoid bound checking.
defconvertToNewString(s):
newString='@'
foriinrange(len(s)):
newString+='#'+s[i]
newString+='#$'
returnnewString
deflongestPalindromeSubstring(s):
Q=convertToNewString(s)
c, r=0, 0# current center, right limit
foriinrange(1, len(Q) -1):
# find the corresponding letter in the palindrome substring
iMirror=c- (i-c)
ifr>i:
P[i] =min(r-i, P[iMirror])
# expanding around center i
whileQ[i+1+P[i]] ==Q[i-1-P[i]]:
P[i] +=1
# Update c, r in case if the palindrome centered at i expands past r
ifi+P[i] >r:
c=i# next center = i
r=i+P[i]
# Find the longest palindrome length in P
maxPalindrome=0
centerIndex=0
foriinrange(1, len(Q) -1):
ifP[i] >maxPalindrome:
maxPalindrome=P[i]
centerIndex=i
returns[(centerIndex-1-maxPalindrome) //2: (centerIndex-1-maxPalindrome) //2+maxPalindrome]
s=input()
print(longestPalindromeSubstring(s))