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。ide
Example:spa
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example:3d
Input: "cbbd" Output: "bb"
動態規劃:code
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算法blog
用 mx 記錄以前計算的最長的迴文子串長度所能到達的最後邊界,用 id 記錄其對應的中心,能夠利用迴文子串中的迴文子串信息。字符串
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 };