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.
利用已发现回文的对称性,不必每次从一个字符开始扩展,从而实现O(n)的复杂度;稍加修改可以在O(n)或者一个串中所有回文的个数。
----------------
class Solution {
public:
string longestPalindrome(string s) {
int len = s.length();
if (len < 2) return s;
string ts = "^#";
for (int i = 0; i < len; i++) {
ts.push_back(s[i]);
ts.push_back('#');
}
ts.push_back('$');
int tlen = ts.length();
int p[tlen];
fill(p, p + tlen, 0);
int C = 1, R = 1;
int mpos = 1, mlen = 1;
for (int i = 1; i < tlen - 1; i++) {
int mirror = 2 * C - i;
p[i] = (R <= C ? 0 : min(mirror >= 0 ? p[mirror] : 0, R - i));
while (ts[i + p[i] + 1] == ts[i - p[i] - 1]) p[i]++;
if (i + p[i] > R) {
C = i;
R = i + p[i];
}
if (p[i] > mlen) {
mpos = i;
mlen = p[i];
}
}
return s.substr((mpos - mlen - 1)/ 2, mlen);
}
};
本文介绍了一种高效算法,用于查找给定字符串中的最长回文子串。通过利用回文字符串的对称特性,该算法能够在O(n)的时间复杂度内完成任务。文中详细解释了如何通过对原始字符串进行预处理并使用中心扩展方法来达到这一目的。
795

被折叠的 条评论
为什么被折叠?



