Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
被这个题卡了好久,还是编程太弱...主要是我觉得有的时候还是想太复杂了,忽略了程序的机械性><
主要思路:
就是solution里给出的最后的那种expand的方法
我总结的是expand的最小单位可以是针对个数为偶数的回文的两个字母,比如说"abba"中的"bb",和针对个数为奇数的回文的三个字母,比如说"dabad"中的"aba"。
还有一个专门用循环找回文的helper function
在循环的时候每次i增加1,因为不增加1,增加比如说回文后半段的长度,可能会跳过正确答案,导致部分测试无法通过
代码如下:
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
length = len(s)
#if length equals 0 or 1, return s
if length == 0 or length == 1:
return s
else:
i = 0
max_len = 0
sub = ''
#两个字母为最小单位
while i < length:
if (i + 1) < length and s[i] == s[i + 1]:
max_len, sub = self.find_palindrome(s, i, i + 1, max_len, sub, length)
i += 1
i = 0
#三个字母为最小单位
while i < length:
if (i + 1) < length and (i - 1) >= 0 and s[i - 1] == s[i + 1]:
max_len, sub = self.find_palindrome(s, i - 1, i + 1, max_len, sub, length)
i += 1
if max_len == 0:
sub = s[0]
return sub
#循环来不断找回文的helper function
def find_palindrome(self, s, i, j, max_len, sub, length):
while i >= 0 and j < length and s[i] == s[j]:
i -= 1
j += 1
i += 1
if j- i > max_len:
max_len = j - i
sub = s[i: j]
return max_len, sub