【题目描述】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.
【解题思路】中心扩展法:以某个元素为中心,分别计算偶数长度的回文最大长度和奇数长度的回文最大长度。
【考查内容】字符串
class Solution {
public:
string longestPalindrome(string s) {
const int len = s.size();
if(len <= 1)return s;
int start, maxLen = 0;
for(int i = 1; i < len; i++){
//寻找以i-1,i为中点偶数长度的回文
int low = i-1, high = i;
while(low >= 0 && high < len && s[low] == s[high]){
low--;
high++;
}
if(high - low - 1 > maxLen){
maxLen = high - low -1;
start = low + 1;
}
//寻找以i为中心的奇数长度的回文
low = i- 1; high = i + 1;
while(low >= 0 && high < len && s[low] == s[high]){
low--;
high++;
}
if(high - low - 1 > maxLen){
maxLen = high - low -1;
start = low + 1;
}
}
return s.substr(start, maxLen);
}
};