https://leetcode.com/problems/longest-palindromic-substring/description/
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.
Input: "cbbd" Output: "bb"
The most important thing is, how to reuse the previous palindromic substring we have worked out? The answer is, only consider new palindromic substrings which are longer than before. For each character, we consider it as the end of substring, then there are two situations: length increase by 1 or length increase by 2, the rest judgement is just simple.
class Solution(object):
def isPalindrome(self, s, begin, end):
if begin < 0:
return False
while begin < end:
if s[begin] != s[end]:
return False
begin += 1
end -= 1
return True
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
currLength = 0
longestP = ""
for i in range(len(s)):
if self.isPalindrome(s, i - currLength - 1, i):
longestP = s[i - currLength - 1: i + 1]
currLength += 2
elif self.isPalindrome(s, i - currLength, i):
longestP = s[i - currLength: i + 1]
currLength += 1
return longestP