题目描述:
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
解题思路:
枚举回文串的中间位置i,然后不断往外扩展,直到有字符不同。同时要注意长度为奇数和偶数的回文串的处理方式不同。
AC代码如下:
class Solution {
public:
string longestPalindrome(string s) {
string ans;
if (s.size() == 0) return ans;
int n = s.size();
int max_len = 0;
for (int i = 0; i < n; ++i){
for (int j = 0; i - j >= 0 && i + j < n; ++j){ //长度为奇数
if (s[i - j] == s[i + j]) {
if (max_len < 2 * j + 1){
max_len = 2 * j + 1;
ans = s.substr(i - j, max_len);
}
}
else{
break;
}
}
for (int j = 0; i - j >= 0 && i + 1 + j < n; ++j){ //长度为偶数
if (s[i - j] == s[i + 1 + j]){
if (max_len < 2 * j + 2){
max_len = 2 * j + 2;
ans = s.substr(i - j, max_len);
}
}
else{
break;
}
}
}
return ans;
}
};