模板—字符串—KMP(单模式串,单文本串)
Code:
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; #define N 1000010 int f[N],n,ans,len1,len2; char str1[N],str2[N]; int main() { scanf("%s%s",str2+1,str1+1),len1=strlen(str1+1),len2=strlen(str2+1); for(int i=1,j=0;i<len1;f[++i]=j) { while(j&&str1[i+1]!=str1[j+1]) j=f[j]; if(str1[i+1]==str1[j+1]) j++; } for(int i=1,j=0;i<=len2;i++) { while(j&&str2[i]!=str1[j+1]) j=f[j]; if(str2[i]==str1[j+1]) j++; if(j==len1) printf("%d ",i-len1+1),j=f[j]; } }