Longest Palindromic Substring
Given a string s, return the longest substring of s that is a palindrome.
A palindrome is a string that reads the same forward and backward.
If there are multiple palindromic substrings that have the same length, return any one of them.
Example 1:
Input: s = "ababd"
Output: "bab"
Explanation: Both “aba” and “bab” are valid answers.
Example 2:
Input: s = "abbc"
Output: "bb"
Constraints:
1 <= s.length <= 1000
s contains only digits and English letters.
Solution
A classic algorithm for palindromic is manacher algorithm, which can compute the longest radius of palindrome taking each character as the center in O ( n ) O(n) O(n) time complexity.
Because we assume that all palindromes have its center, the length of all palindromes should be odd. To achieve this property, we can insert special characters, like #
between each character in the original string, e.g. abba
->#a#b#b#a#
.
Now, assuming d [ i ] d[i] d[i] denotes the longest radius of palindrome whose center locates at i i i, how can we use the information acquired before? Thinking about the property of palindrome, if i i i is in a palindrome centered on j ( j + d [ j ] > i ) j\ (j+d[j]>i) j (j+d[j]>i), then i i i’s symmetric character of j j j, j + j − i j+j-i j+j−i would be helpful. The overlapping part of palindromes centered on j + j − i j+j-i j+j−i and j j j would be the same for palindrome centered on i i i. The next we need to do is to see if we can expand d [ i ] d[i] d[i] to exceed j + d [ j ] j+d[j] j+d[j] and update j j j, which denotes the center of palindrome whose right endpoint is the largest. Because each time we update d [ i ] d[i] d[i], i i i or j + d [ j ] j+d[j] j+d[j] will be at least be plused by 1. So, the whole process can be done in O ( n ) O(n) O(n) time complexity.
Code
class Solution:
def longestPalindrome(self, s: str) -> str:
seq = ['#']
for c in s:
seq.append(c)
seq.append('#')
d = [0]*len(seq)
center = 0
max_center = 0
for i in range(1, len(seq)):
if center + d[center] > i:
d[i] = min(center+d[center]-i, d[center+center-i])
while i-d[i]-1 >= 0 and i+d[i]+1 < len(seq) and seq[i-d[i]-1] == seq[i+d[i]+1]:
d[i] += 1
if center + d[center] < i + d[i]:
center = i
if d[i] >= d[max_center]:
max_center = i
print(seq)
print(d)
ans = []
for i in range(max_center-d[max_center], max_center+d[max_center]+1):
if seq[i] != '#':
ans.append(seq[i])
return ''.join(ans)