最长回文子串O(n)

 1 #include<vector>
 2 #include<iostream>
 3 #include<cstdio>
 4 #include<string.h>
 5 using namespace std;
 6 
 7 const int N=3000010;
 8 int n, p[N];
 9 char s[N], str[N];
10 
11 #define _min(x, y) ((x)<(y)?(x):(y))
12 
13 void kp()
14 {
15     int i;
16     int mx = 0;
17     int id;
18     for(i=n; str[i]!=0; i++)
19         str[i] = 0; 
20     for(i=1; i<n; i++)
21     {
22         if( mx > i )
23             p[i] = _min( p[2*id-i], p[id]+id-i );
24         else
25             p[i] = 1;
26         for(; str[i+p[i]] == str[i-p[i]]; p[i]++)
27             ;
28         if( p[i] + i > mx )
29         {
30             mx = p[i] + i;
31             id = i;
32         }
33     }
34 }
35 
36 void init()
37 {
38      int i, j, k;
39      str[0] = '$';
40      str[1] = '#';
41      for(i=0; i<n; i++)
42      {
43       str[i*2+2] = s[i];
44       str[i*2+3] = '#';
45      }
46      n = n*2+2;
47      s[n] = 0;
48 }
49 
50 int main()
51 {
52     int i, ans;
53     int t;
54     cin >> t;
55     while(t--)
56     {
57         cin >>s;
58         n = strlen(s);
59         init();
60         kp();
61         ans = 0;
62         for(i=0; i<n; i++)
63             if(p[i]>ans)
64                 ans = p[i];
65         printf("%d\n", ans-1);
66     }
67     return 0;
68 }
代码君

 

posted @ 2014-12-12 18:05  UsedRose  阅读(156)  评论(0编辑  收藏  举报