最长回文子串——中心扩展法
解法思路
- 首先考虑到从中心向两边扩展的两种情况,一种是对称中心就是某个元素,另一种是对称中心在两个元素之间。所以中心扩展函数的形参列表中有两个指针,分别向前和向后搜索。依次遍历字符串中的每个字符时,分两种情况,第一种是以当前字符为中心,则传入的头尾指针指向的都是当前字符;第二种情况是头指针指向当前字符,尾指针指向当前字符的后一个字符。比较这两种返回的字符串长度,去较长的那一个保留。
- 所以在设计中心扩展函数的时候就要考虑到这一点,中心扩展函数中有两个指针(head和tail),head向左搜索,tail向右搜索,如果各自指向的元素相等就继续,否则停止搜索,并返回substring[head+1, tail-1]之间的元素(因为此时head和tail指向的元素已经不是相等的了)
代码实现
class Solution {
public:
string longestPalindrome(string s) {
if(s.size() < 2){return s;}
string result = "";
for(int i = 0; i < s.size(); i++){
string temp = "";
string oddstr = centerSpread(s, i, i);
string evenstr = centerSpread(s, i, i+1);
temp = oddstr.size() > evenstr.size() ? oddstr: evenstr;
if(temp.size() > result.size()){
result = temp;
}
}
return result;
}
string centerSpread(string str, int head, int tail){
int i = head;
int j = tail;
while((i>=0) && (j < str.size())){
if(str[i] == str[j]){
i--;
j++;
}
else{
break;
}
}
return str.substr(i+1, j-i-1);
}
};