leetcode - Longest Palindromic Substring

来源:互联网 发布:qq直播是什么软件 编辑:程序博客网 时间:2024/06/07 13:14

题目:

Longest Palindromic Substring

 

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.


分析:

运用manacher算法,实现O(n)时间复杂度。参考这里。

class Solution {public:string longestPalindrome(string s) {if (s.empty())return s;if (s.size() <= 2){if (s[0] == s[s.size() - 1])return s;elsereturn s.substr(0, 1);}int size = s.size();string str(2 * size + 1, '#');for (int i = 0, j = 1; i<size; ++i, j += 2){str[j] = s[i];}size = str.size();vector<int> f(size, 0);f[1] = 2;//max_len是str最大半径,max_center是取值max_len时的下标int max_len = 2, max_center = 1;//cur_right是当前半径向右延伸所能到达的最大下标,center是取值cur_right时的下标int cur_right = 2, center = 1;for (int i = 2; i <= size - 3; ++i){if (i>cur_right){int r = 1;while (i - r >= 0 && i + r<size && str[i - r] == str[i + r])++r;f[i] = r;}else{int i2 = center * 2 - i, i2_left = i2 - f[i2] + 1, center_left = center - f[center] + 1;if (i2_left<center_left){f[i] = cur_right - i + 1;}else if (i2_left == center_left){int r = cur_right - i + 1;while (i - r >= 0 && i + r<size && str[i - r] == str[i + r])++r;f[i] = r;}else{f[i] = f[i2];}}//更新max_len和max_centerif (f[i]>max_len){max_len = f[i];max_center = i;}//更新cur_right和centerif (i + f[i] - 1>cur_right){cur_right = i + f[i] - 1;center = i;}}string res = str.substr(max_center - max_len + 1, 2 * max_len - 1);//删除字符 '#'res.erase(remove(res.begin(), res.end(), '#'), res.end());return res;}};


0 0
原创粉丝点击