Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
求最大回文子串,考虑回文串的特点:依据中心点左右对称,分为两种情况,字符串长度为奇数时“aba”和长度为偶数时“abba”.
给定一个字符串求其最大回文串串,可以考虑回文串中心点的位置,依次遍历每一个字符作为回文串的中心点,考虑奇偶两种情况:
当为奇数时,可以双指针i,i直接向两边遍历,直到两指针的下一个字符不相等,即两指针此时指向最长的回文串起始点;
当为偶数时,利用双指针i,i+1,依次向两边遍历求解,直到两指针的下一个字符不相等,即两指针此时指向最长的回文串起始点。
def helper(s, i, j):
if s[i]!=s[j]:
return 1, i
while i>0 and j<len(s)-1:
if s[i-1]==s[j+1]:
i -= 1
j += 1
else:
break
return j-i+1,i
当字符串长度为偶数并且初始s[i]!=s[j=i+1],可以直接返回
否则此时i,j指向了回文串的起始点,奇数指向同一个字符,偶数指向前后不同字符
完整程序如下:
第一个写python调试程序,辅助方法写进类内,一直调试不通过,后来查了一下,如果方法写入类内,需要方法声明self变量
def helper(s, i, j):
if s[i]!=s[j]:
return 1, i
while i>0 and j<len(s)-1:
if s[i-1]==s[j+1]:
i -= 1
j += 1
else:
break
return j-i+1,i
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
if len(s)==1:
return s
maxlength = 0
lo = 0
for i in range(len(s)-1):
m1,i1 = helper(s, i, i+1)
if m1>=maxlength:
lo = i1
maxlength = m1
#print (m1, i1, i1+maxlength)
m2,i2 = helper(s, i, i)
if m2>=maxlength:
lo = i2
maxlength = m2
#print (m2, i2, i2+maxlength)
#maxlength = max(maxlength, helper(s, i, i+1), helper(s, i, i))
#print (lo, s[lo:lo+maxlength], maxlength)
return s[lo:lo+maxlength]
看了一下大神的程序又改了一下:简洁了很多:
class Solution:
def helper(self, s, i, j):
if s[i]!=s[j]:
return s[i]
while i>0 and j<len(s)-1:
if s[i-1]==s[j+1]:
i -= 1
j += 1
else:
break
return s[i:j+1]
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
if len(s)==1:
return s
r = ''
for i in range(len(s)-1):
l1 = self.helper(s, i, i+1)
if len(l1)>=len(r):
r = l1
l2 = self.helper(s, i, i)
if len(l2)>=len(r):
r = l2
return r
python中类方法的定义: