题目描述:
给定一个字符串s
,找到s
中最长的回文子串。你可以假设s
的最大长度为1000。
示例 1:
输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
示例 2:
输入: "cbbd"
输出: "bb"
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindromic-substring
解题方法 :
1、暴力法会超出时间限制。
2、中心扩展,把字符串的每一位/相同的两位作为回文串的中心,向两边扩展,找最长的,时间效率O(n^2)。
class Solution {
public:
string longestPalindrome(string s) {
if(s.size() <=1) return s;
string result,temp;
int start,end,num=-1;
for(int i = 0; i < s.size(); i++){
int j=i-1,k=i+1;
start=i;
end=i;
while( j>=0 && k<s.size()){
if(s[j] == s[k]){
start = j;
end = k;
j--;
k++;
}
else break;
}
if(end-start > num){
result = s.substr(start,end-start+1);
num = end-start;
}
}
for(int i = 0; i < s.size()-1; i++){
if(s[i] != s[i+1]) continue;
start = i;
end = i+1;
int j=i-1,k=i+2;
while( j>=0 && k<s.size()){
if(s[j] == s[k]){
start = j;
end = k;
j--;
k++;
}
else break;
}
if(end-start > num){
result = s.substr(start,end-start+1);
num = end-start;
}
}
return result;
}
};