#include<stdio.h> #include<string.h> const int INF =1000005; /* 3 BAPC BAPC AZA AZAZAZA VERDI AVERDXIVYERDIAN Sample Output 1 3 0 */ int n,m; char str[INF] ; //主串 char p[INF]; //模式串 int nextval[INF]; void get_nextval(); //获取nextval数组 int KmpSearch(); //kmp匹配 int main() { int T; scanf("%d",&T); while(T--) { scanf("%s",p); scanf("%s",str) ; n = strlen(str); m = strlen(p); get_nextval(); int result = KmpSearch(); printf("%d\n",result); } return 0; } void get_nextval() { int i = -1; int j = 0; nextval[0] = -1; while(j < m) { if(i == -1 || p[i] == p[j]) { i++; j++; if(p[i] != p[j]) { nextval[j] = i; } else { nextval[j] = nextval[i]; } } else i = nextval[i]; } } int KmpSearch() { int i = 0; int j = 0; int result = 0; //一共有多少个匹配 while(i < n) { if(str[i] == p[j] || j == -1) { i++; j++; } else { j = nextval[j]; } if(j == m) //表示完成一个匹配 { result++; printf("%d ",i - j); //输出这个匹配在主串开始的位置(注意,主串是从0开始的) j = nextval[j]; } } printf("\n"); return result; }
KMP模版(输出多个匹配)
猜你喜欢
转载自blog.csdn.net/u013377068/article/details/80070081
今日推荐
周排行