5. 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.
给定字符串,从中找出最长的回文串,假设最长不超过1000.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Input: "cbbd"
Output: "bb"
Solutions:
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
res = ""
for i in range(len(s)):
tmp = self.segment(s, i, i)
if len(tmp) > len(res):
res = tmp
tmp = self.segment(s, i, i+1)
if len(tmp) > len(res):
res = tmp
return res
def segment(self, s, l, r):
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
return s[l+1:r]