LeetCode: Longest Palindromic Substring

Just as the problem name, our goal is to find the longest palindromic substring in the original string. Of course, we can manage to make it in O(n^2). However, I use a really wonderful algorithm to solve this problem in O(n).

The algorithm is called Manacher Algorithm. You can find more details about the algorithm in this page

Here is my solution:

01 class Solution
02 {
03 public:
04     string longestPalindrome(string s)
05     {
06         string t="$";
07         for(int i=0;i<s.size();i++)
08             t+='#',t+=s[i];
09         t+='#';
10         get(t);
11         int ans=0,pos;
12         string str="";
13         for(int i=1;i<t.size();i++)
14             if(p[i]>ans)
15             {
16                 ans=p[i];
17                 pos=i;
18             }
19         for(int i=posans+1;i<pos+ans;i++)
20             if(t[i]!='#') str+=t[i];
21         return str;
22     }
23     int p[2010];
24     void get(string str)
25     {
26         int mx=0,id;
27         for(int i=1;i<str.size();i++)
28         {
29             if(mx>i) p[i]=min(p[2*idi],mxi);
30             else p[i]=1;
31             for(;str[i+p[i]]==str[ip[i]];p[i]++)
32                 ;
33             if(p[i]+i>mx)
34             {
35                 mx=p[i]+i;
36                 id=i;
37             }
38         }
39     }
40 };
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s