题目:http://poj.org/problem?id=2406
题意:找a的n次方,与s串匹配。
#include<stdio.h>
#include<string.h>
const int max=1000005;
char str[max];
int len,next[max],ans[max];
void get_next(){
int i=0,j=-1;
next[0]=-1;
while(i<len){
if(j==-1||str[i]==str[j]){
i++;
j++;
if (str[i] != str[j]) /*这里有一个kmp的优化*/
next[i] = j;
else
next[i] = next[j];
}
else
j=next[j];
}
}
main(){
while(scanf("%s",str)!=EOF&&strcmp(str,".")!=0){
len=strlen(str);
get_next();
if(len%(len-next[len])==0)
//if(next[len]>=len/2)
printf("%d\n",len/(len-next[len]));
else
printf("1\n");
}
}
本文介绍了一种高效的字符串匹配算法——KMP算法,并通过一个具体的编程实例详细展示了该算法的工作原理及其应用过程。KMP算法能够有效避免传统模式匹配中出现的部分重复比较,大大提升了字符串匹配效率。
626

被折叠的 条评论
为什么被折叠?



