题意:求出一个字符串的最长回文子串,如"babad"输入“bab”
思路:首先可以枚举每个点,以该点为中心扩展,取扩展半径最大的为答案。由于偶数长度串中心为两个点,故可以在两点间插入一个任意字符使得不管奇数偶数串都变为奇数串来处理
class Solution {
public:
string longestPalindrome(string s) {
int maxx = 0;
string s2 = "#", res = "", ans = "";
if (s.length() == 1)
return s;
int t = s.length();
for (int i = 0; i < s.length(); i++) {
s2 = s2 + s[i] + "#";
}
for(int i = 1; i < s2.length(); i++) {
for (int j = 1; i-j >= 0 && i+j < s2.length(); j++) {
if (s2[i-j] == s2[i+j]) {
if (j > maxx) {
maxx = j;
res = s2.substr(i-j, j*2+1);
}
} else {
break;
}
}
}
for (int i = 0; i < res.length(); i++)
if (res[i] != '#')
ans = ans + res[i];
return ans;
}
};
最长回文子串的典型解决算法是Manacher,即优化过后的中心扩展法,根据对称点防止匹配失败后返回起始点从头开始匹配
class Solution {
public:
string longestPalindrome(string s) {
int maxx = 0, flag = 0, ans = 0;
string s2 = "$#", res = "", res2 = "";
for (int i = 0; i < s.length(); i++) {
s2 = s2 + s[i] + "#";
}
int cnt[s2.length()];
for(int i = 0; i < s2.length(); i++) {
cnt[i] = maxx > i ? min(cnt[2*flag-i], maxx-i) : 1;
while (i+cnt[i] < s2.length() && i-cnt[i] >= 0 && s2[i+cnt[i]] == s2[i-cnt[i]]) {
cnt[i]++;
}
if (i + cnt[i] > maxx) {
maxx = i + cnt[i];
flag = i;
}
if (cnt[i] > ans && i-cnt[i] >= 0) {
ans = cnt[i];
res = s2.substr(i-cnt[i]+1, (cnt[i]-1)*2+1);
}
}
for (int i = 0; i < res.length(); i++) {
if (res[i] != '#')
res2 = res2 + res[i];
}
return res2;
}
};