Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example:
Input: "cbbd" Output: "bb"
Subscribe to see which companies asked this question
class Solution(object):
def findPalindrome(self, s, index):
step = 0
i = index - 1
j = index + 1
while i >= 0 and j< len(s):
if s[i] == s[j]:
i -= 1
j += 1
step += 1
else:
break
return step
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
s_temp = ['#']
for s_t in s:
s_temp.append(s_t)
s_temp.append('#')
steps = [0]*len(s_temp)
C = L = R = 0
for i in range(len(s_temp)):
i_l = 2*C - i
if i_l < 0 or steps[i_l] >= R - i:
steps[i] = self.findPalindrome(s_temp, i)
C = i
L = i - steps[i]
R = i + steps[i]
else:
steps[i] = steps[i_l]
m_index = steps.index(max(steps))
result = []
L = R = m_index
i = 0
while i <= steps[m_index]:
if L == R:
if s_temp[L] != '#':
result.append(s_temp[L])
else:
if s_temp[L] != '#':
result.insert(0,s_temp[L])
if s_temp[R] != '#':
result.append(s_temp[R])
i += 1
L -= 1
R += 1
return ''.join(result)
译文在此: [译+改]最长回文子串(Longest Palindromic Substring) Part II
这道题我采用的思路是Manacher算法,其主要思想先将字符与字符之间插入#号,这样从中间往两边找的时候,就不用奇偶序列分别考虑了。
然后在从前到后遍历的过程中,利用前面的中心轴对称性质,可以简化掉一部分计算。详见链接文章。