Description
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"
分析
题目的意思是:找出一个字符串中的最长回文子串。
- 这道题从中间开花,遍历每个结点,把每个节点都当作回文子串的中心位置,然后向左右拓展,找出所有这种回文子串中最长的就够了。
C++代码
class Solution {
public:
string longestPalindrome(string s) {
int max_len=0;
int start=0;
for(int i=0;i<s.length();i++){
int left=i-1;
int right=i+1;
while(left>=0&&right<s.length()&&s[left]==s[right]){
int cur_len=right-left;
if(cur_len>max_len){
max_len=cur_len;
start=left;
}
left--;
right++;
}
left=i;
right=i+1;
while(left>=0&&right<=s.length()&&s[left]==s[right]){
int cur_len=right-left;
if(cur_len>max_len){
max_len=cur_len;
start=left;
}
left--;
right++;
}
}
return s.substr(start,max_len+1);
}
};
Python代码
使用中心扩散法,要考虑两种情况,第一种是aba的形式,第二种是abba的形式。
class Solution:
def expand_center(self,s, left, right):
while(left>=0 and right<len(s) and s[left]==s[right]):
left-=1
right+=1
return left+1,right-1
def longestPalindrome(self, s: str) -> str:
n = len(s)
max_len = 0
for i in range(n):
left,right = self.expand_center(s,i,i)
if(right-left+1>max_len):
max_len=right-left+1
result= s[left:right+1]
left,right = self.expand_center(s,i,i+1)
if(right-left+1>max_len):
max_len=right-left+1
result= s[left:right+1]
return result
参考文献
Manacher’s Algorithm 马拉车算法
LeetCode 5. Longest Palindromic Substring(最长回文连续子串)
[Leetcode] Longest palindromic substring 最长回文子串
Longest Palindromic Substring Part II