Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
给出一个字符串S,找到一个最长的连续回文串。你可以假设s的最大长度是1000。
Example:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example:
Input: "cbbd" Output: "bb"
动态规划:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 class Solution { 2 public: 3 string longestPalindrome(string s) { 4 if (s.empty()) return ""; 5 if (s.size() == 1) return s; 6 7 int min_start = 0; 8 int max_len = 1; 9 int n = s.size(); 10 for (int i = 0; i < n;) { 11 int j = i, k = i; 12 while (k < n-1 && s[k] == s[k+1]) {//k——k+1表示相等的同一个元素 13 k++; 14 } 15 i = k + 1; 16 while (k < n-1 && s[k+1] == s[j-1] && j > 0) {//j-1——k+1为对称相等的元素 17 ++k; 18 --j; 19 } 20 21 int new_len = k - j + 1;//当前回文串大小 22 if (new_len > max_len) { 23 min_start = j; 24 max_len = new_len; 25 } 26 } 27 return s.substr (min_start, max_len); 28 } 29 };
?Manacher’s Algorithm算法
用 mx 记录之前计算的最长的回文子串长度所能到达的最后边界,用 id 记录其对应的中心,可以利用回文子串中的回文子串信息。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 class Solution { 2 public: 3 string longestPalindrome(string s) { 4 string t ="$#"; 5 for (int i = 0; i < s.size(); ++i) { 6 t += s[i]; 7 t += '#'; 8 } 9 int p[t.size()] = {0}, id = 0, mx = 0, resId = 0, resMx = 0; 10 for (int i = 0; i < t.size(); ++i) { 11 p[i] = mx > i ? min(p[2 * id - i], mx - i) : 1; 12 while (t[i + p[i]] == t[i - p[i]]) ++p[i]; 13 if (mx < i + p[i]) { 14 mx = i + p[i]; 15 id = i; 16 } 17 if (resMx < p[i]) { 18 resMx = p[i]; 19 resId = i; 20 } 21 } 22 return s.substr((resId - resMx) / 2, resMx - 1); 23 } 24 };