【模板】kmp

  题目描述

  给出两个字符串 s1 和 s2,若 s_1s1 的区间 [l,r] 子串与 s2 完全相同,则称 s2 在 s1 中出现了,其出现位置为 l。
  现在请你求出 s2 在 s1 中所有出现的位置。

  输入格式

  第一行为一个字符串,即为 s1
  第二行为一个字符串,即为 s2

  输出格式

  输出若干行,每行一个整数,按从小到大的顺序输出 s2 在 s1 中出现的位置。


 附贴一个很好的BLOG

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<cmath>
 5 using namespace std;
 6 int next[1000001];
 7 void get_next(string x,int len){
 8     next[0]=-1;
 9     for(int i=1;i<=len-1;i++){
10         int j=next[i-1];
11         while((x[i]!=x[j+1])&&(j>=0)) j=next[j];
12         if(x[i]==x[j+1]) next[i]=j+1;
13         else next[i]=-1;
14     }
15 }
16 void kmp(string x,string y,int len_x,int len_y){
17     int i=0,j=0;
18     while(i<=len_x-1){
19         if(x[i]==y[j]){
20             i++;
21             j++;
22             if(j==len_y){
23                 printf("%d\n",i-j+1);
24                 j=next[j-1]+1;
25             }
26         }
27         else{
28             if(j==0) i++;
29             else j=next[j-1]+1;
30         }
31     }
32 }
33 int main(){
34     string str1,str2;
35     int len1,len2;
36     cin>>str1>>str2;
37     len1=str1.size();
38     len2=str2.size();
39     get_next(str2,len2);
40     kmp(str1,str2,len1,len2);41 }

 

posted @ 2020-08-20 15:31  latent_Lin  阅读(133)  评论(0)    收藏  举报