当前位置: 代码迷 >> 综合 >> 5. Longest Palindromic Substring的O(N)解法
  详细解决方案

5. Longest Palindromic Substring的O(N)解法

热度:25   发布时间:2023-11-24 00:49:19.0

马拉车算法,每次维护对称区能达到的最右位置。

class Solution {
public:string longestPalindrome(string s) {string str;int p[2005];str = "?#";int i;int l = s.length();for (i = 0; i < l; i++)str += s[i], str += '#';//cout << str << endl;int pos = 0, mx = 0;int l1 = str.length();int rm = 0, rc = 0;for (int i = 1; i < l1; i++){if (i < mx)p[i] = min(p[2 * pos - i], mx - i);else p[i] = 1;while (str[i + p[i]] == str[i - p[i]])p[i]++;if (mx < i + p[i])mx = i + p[i], pos = i;if (rm < p[i] - 1)rm = p[i] - 1, rc = i;}int r = p[pos]-1;string ss;if (rm != 0){for (int i = rc - rm; i <= rc + rm; i++){if (str[i] != '#')ss += str[i];}}return ss;}
};

 

  相关解决方案