Description
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"
Code
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
start, end = 0, 0
for idx in range(len(s)):
len1 = self.cntLen(s, idx, idx + 1)
len2 = self.cntLen(s, idx, idx)
l = max(len1, len2)
if l > start - end:
start = idx - (l - 1) / 2
end = idx + l / 2
return s[start:end + 1]
def cntLen(self, s, l, r):
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
return r - l - 1
Conclusion
这道题没有想到方法,是照着solution写的,还有别的方法可以学习。该题教程