1 #include <iostream>
2 using namespace std;
3
4 void substring(char* str)
5 {
6 int len = strlen(str);
7 len = 2*len + 1;
8 for(int i = len; i >= 1; i--)
9 {
10 if(i%2 == 0)
11 str[i-1] = str[i/2-1];
12 else
13 str[i-1] = '#';
14 }
15 str[len] = '\0';
16 int* p = new int[len]; //p[i]用来保存第i个字符为中心的回文字串向右/向左扩张的距离
17 int mx = 0; //表示已经处理的回文字串向右扩张的最长距离
18 int id = 0; //表示上述回文子串的中间位置
19 memset(p,0,len);
20 for(int i = 0; i < len; i++)
21 {
22 if(mx - i > 0)
23 {
24 p[i] = p[2*id - i] < (mx - i)?p[2*id - i]:(mx-i);
25 }
26 else
27 p[i] = 1;
28 while(str[i + p[i]] == str[i - p[i]]) p[i]++;
29 if(p[i] > mx - i)
30 {
31 mx = i + p[i];
32 id = i;
33 }
34 }
35 mx = 0;
36 id = 0;
37 for(int i = 0; i < len; i++)
38 {
39 if(p[i] > mx)
40 {
41 mx = p[i];
42 id = i;
43 }
44 }
45 cout<<"最长回文字串:";
46 for(int i = id-mx+1; i < id+mx; i++)
47 {
48 if(str[i] != '#')
49 cout<<str[i];
50 }
51 cout<<endl;
52 }
53 int main()
54 {
55 while(1)
56 {
57 char* str = new char[100];
58 if(str == NULL)
59 return 0;
60 cout<<"输入字符串:";
61 cin>>str;
62 substring(str);
63 delete[] str;
64 str = NULL;
65 }
66 return 0;
67 }