链接:Longest Palindromic Substring
思路:从字符串左边开始遍历,每个i假设为回文的最中心,略过重复字符,然后向左右两边比较字符是否相同,
直到碰到不相同的,记录长度,如果长度大于最大回文长度,替换,否则放弃。
代码:
class Solution {
public:
string longestPalindrome(string s) {
if (s.size() <= 1){
return s;
}
int begin = 0;
int maxLen = 1;
for (int i=0; i<s.size() && (s.size()-i)*2>= maxLen;){
int left=i, right = i;
//跳过重复的元素
while (right < s.size()-1 && s[right] == s[right+1]){ right ++; }
i = right+1; //右边非重复的第一个
while (left>0 && right<s.size() && s[left-1]==s[right+1]){
left --;
right ++;
}
if (maxLen<(right-left+1)){
maxLen = right-left+1;
begin = left;
}
}
return s.substr(begin, maxLen);
}
};
public:
string longestPalindrome(string s) {
if (s.size() <= 1){
return s;
}
int begin = 0;
int maxLen = 1;
for (int i=0; i<s.size() && (s.size()-i)*2>= maxLen;){
int left=i, right = i;
//跳过重复的元素
while (right < s.size()-1 && s[right] == s[right+1]){ right ++; }
i = right+1; //右边非重复的第一个
while (left>0 && right<s.size() && s[left-1]==s[right+1]){
left --;
right ++;
}
if (maxLen<(right-left+1)){
maxLen = right-left+1;
begin = left;
}
}
return s.substr(begin, maxLen);
}
};