Reprint: Please indicate the source, http://blog.csdn.net/zonghongyan314/article/details/41787877, thank you.
Recently read a more interesting algorithm for the length of the largest symmetric substring in the string, share with you.
Idea: Use the next array to prevent a rollback comparison, for example: String str: "ABCXXXXXCBVVVVV", which corresponds to the next array value:
|
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
| Str: |
A |
B |
C |
X |
X |
X |
X |
X |
C |
B |
V |
V |
V |
V |
V |
| Next |
1 |
1 |
1 |
1 |
2 |
3 |
4 |
5 |
7 |
9 |
1 |
2 |
3 |
4 |
5 |
The time complexity of the "Dead Knock Class" algorithm is increased to O (n). With KMP next similar O (∩_∩) o~, but unfortunately has not yet understood KMP.
#include <iostream> using namespace std; /**************************************************** ******* @Author Renzi ****2014 year December 7 **************** function: Enter a string
, output the length of the largest symmetric substring in the string for example: "ABACC" returns 3, "a" returns 1,ABB returns 4; Input: String str returns: the length of the maximum symmetric substring of int *****************************************************/int strsymmetriccounts (const char*
STR);
int main () {char* str= "ABCXXXXXXXXCCCCC";
printf ("Source string:%s\n", str);
int len = strsymmetriccounts (str);
printf ("Maximum symmetric substring length:%d\n", Len);
return 0;
int strsymmetriccounts (const char* str) {if (str==null) return-1;
int Len=strlen (str);
int maxlen=1;
The int next[30];//next array resembles the next array next[0]=1 in KMP;
int i=1;
while (i<len) {int max=1; if ((i-next[i-1]-1) >=0 && str[i]==str[i-next[i-1]-1]) {//rollback compare Max = max > (next[i-1]+2) through next array? Max: (
NEXT[I-1]+2);
int k=1;
while (Str[i]==str[i-k])//If the array of strings is adjacent equal k++;
max = max > k?max:k; next[i]=max;//assigns the next array cout<< "next[" <<i<< "]=" <<next[i]<< ";
"<<endl;
if (Next[i]>maxlen) {maxlen=next[i];
} i++;
return maxlen; }