首页 > 代码库 > LeetCode Longest Palindromic Substring
LeetCode Longest Palindromic Substring
class Solution {private: const char sep_char = ‘\1‘;public: string longestPalindrome(string s) { int max_len = 0; int len = s.length(); if (len <= 1) return s; string str; str.push_back(sep_char); for (int i=0; i<len; i++) { str.push_back(s[i]); str.push_back(sep_char); } int nlen = 2 * len + 1; vector<int> P(nlen, 0); int last_i = 0; int last_r = 0; int maxv = -1; int maxi = -1; for (int i=0; i<nlen; i++) { int p = i, q = i; if (i < last_r) { int j = 2 * last_i - i; // (i + j) / 2 = last_i int slen = min(P[j], last_r - i); p-= slen; q+= slen; } while(p >= 0 && q < nlen && str[p] == str[q]) p--, q++; if (q > last_r) { last_r = q; last_i = i; } P[i] = q - i; if (P[i] > maxv) { maxv = P[i]; maxi = i; } } return s.substr((maxi + 1 - P[maxi]) / 2, P[maxi] - 1); }};
Manacher算法实现,不能懈怠
LeetCode Longest Palindromic Substring
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。