最长回文子串:
1. 暴力搜索 时间复杂度O(n^3)
2. 动态规划
- dp[i][j] 表示子串s[i…j]是否是回文
- 初始化:dp[i][i] = true (0 <= i <= n-1); dp[i][i-1] = true (1 <= i <= n-1); 其余的初始化为false
- dp[i][j] = (s[i] == s[j] && dp[i+1][j-1] == true)
时间复杂度O(n^2),空间O(n^2)
3. 以某个元素为中心,分别计算偶数长度的回文最大长度和奇数长度的回文最大长度。时间复杂度O(n^2),空间O(1)
4. Manacher算法,时间复杂度O(n), 空间复杂度O(n)。 具体参考如下链接:
http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-ii.html
class Solution {
public:
string longestPalindrome(string s) {
int n = *s.length() + ;
char cstr[n];
cstr[] = '\1';
cstr[n-] = '\0';
for(int i = ; i < n; i += )
cstr[i] = '#';
for(int i = ; i < n; i += )
cstr[i] = s[i/ - ];
int *p;
p = new int[n];
memset(p, , sizeof(int)*n); int mx, id, i, j;
for (id = , i = , mx = ; i < n; ++i) {
j = *id - i;
p[i] = (mx > i) ? min(p[j], mx-i) : ;
while (cstr[i + p[i] + ] == cstr[i - (p[i] + )])
++p[i];
if (i + p[i] > mx){
id = i;
mx = id + p[id];
}
} int max = -;
for (i = ; i < n-; ++i) {
if (max < p[i]) {
max = p[i];
id = i;
}
}
return s.substr( (id - max - )/ , max);
}
private: };