轉載:請註明出處,http://blog.csdn.net/zonghongyan314/article/details/41787877,謝謝。
最近看了一個關於求字串中最大對稱子串的長度的比較有意思的演算法,與大家分享一下。
思路:借用next數組防止回朔比較,例如:字串str:"abcxxxxxcbvvvvv",它對應的next數組值:
| |
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 |
將“死磕類”的演算法時間複雜度提高到O(n)。與KMP的next異曲同工O(∩_∩)O~, 只可惜至今沒有理解KMP。
#include<iostream>using namespace std;/***********************************************************@Author仁子欣****2014年12月7號****************功能:輸入一個字串,輸出該字串中最大對稱子串的長度例如:"abacc"返回3,"a"返回1,abb返回4;輸入:字串str返回:int最大對稱子串的長度*****************************************************/int StrSymmetricCounts(const char* str);int main(){ char* str="abcxxxxxxxxccccc";printf("源字串為:%s\n",str);int len = StrSymmetricCounts(str);printf("最大對稱子串長度:%d\n",len);return 0;}int StrSymmetricCounts(const char* str){if(str==NULL)return-1;int len=strlen(str);int maxlen=1;int next[30];//next數組類似KMP中的next數組 next[0]=1;int i=1;while(i<len){int max=1;if((i-next[i-1]-1)>=0 && str[i]==str[i-next[i-1]-1]){//通過next數組回退比較max = max > (next[i-1]+2) ? max: (next[i-1]+2);}int k=1;while(str[i]==str[i-k])//如果字串的數組相鄰的相等k++;max = max > k?max: k;next[i]=max;//將next數組進行賦值cout<<"next["<<i<<"]="<<next[i]<<"; "<<endl;if(next[i]>maxlen){maxlen=next[i]; } i++;}return maxlen;}