最长回文子串:
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 = 2*s.length() + 3; char cstr[n]; cstr[0] = ‘\1‘; cstr[n-1] = ‘\0‘; for(int i = 1; i < n; i += 2) cstr[i] = ‘#‘; for(int i = 2; i < n; i += 2) cstr[i] = s[i/2 - 1]; int *p; p = new int[n]; memset(p, 0, sizeof(int)*n); int mx, id, i, j; for (id = 1, i = 2, mx = 0; i < n; ++i) { j = 2*id - i; p[i] = (mx > i) ? min(p[j], mx-i) : 0; while (cstr[i + p[i] + 1] == cstr[i - (p[i] + 1)]) ++p[i]; if (i + p[i] > mx){ id = i; mx = id + p[id]; } } int max = -1; for (i = 2; i < n-2; ++i) { if (max < p[i]) { max = p[i]; id = i; } } return s.substr( (id - max - 1)/ 2 , max); } private: };
时间: 2024-10-15 15:00:36