标签:
problem:
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.
solution:manacher algorithm
class Solution { public: string longestPalindrome(string s) { string pstr=preProcess(s); const int len=pstr.size(); int p[len]; //用来记录回文串的长度 p[0]=0; int mx=0,max_len=0,po=0,center_index=0; for(int i=1;i<len-1;i++) { if(mx>i) p[i]=min(mx-i,p[2*po-i]); else p[i]=0; while(pstr[i-1-p[i]]==pstr[i+1+p[i]]) p[i]++; if(p[i]+i>mx) { mx=p[i]+i; po=i; } if(p[i]>max_len) { max_len=p[i]; center_index=i; } } return s.substr((center_index-1-max_len)/2,max_len); } string preProcess(string s) { int n=s.size(); if(n==0) return "@"; string result="@"; for(int i=0;i<n;i++) { result.append("#"+s.substr(i,1)); } result.append("#$"); return result; } };
LeetCode:Longest Palindromic Substring
标签:
原文地址:http://www.cnblogs.com/xiaoying1245970347/p/4581252.html