标签:
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.
class Solution { public: string preProcess(string s) { string res; int n=s.length(); if(0==n) { res="~@"; return res; } res="~"; for(int i=0;i<n;i++) res+="#"+s.substr(i,1); res+="#@"; return res; } string longestPalindrome(string s) { string T=preProcess(s); int n=T.length(); int *p=new int[n]; int C=0; int R=0; for(int i=1;i<n-1;i++) { int i_mirror=2*C-i; p[i]=(R>i)?min(R-i,p[i_mirror]):0; while(T[i-p[i]-1]==T[i+p[i]+1]) { p[i]++; } if(i+p[i]>R) { R=i+p[i]; C=i; } } int maxlen=0; int center=0; for(int i=1;i<n-1;i++) { if(p[i]>maxlen) { maxlen=p[i]; center=i; } } delete []p; return s.substr((center-1-maxlen)/2,maxlen); } };
leetcode[5]Longest Palindromic Substring
标签:
原文地址:http://www.cnblogs.com/Vae98Scilence/p/4283719.html