KMP

 1 # include<iostream>
 2 # include<cstring>
 3 using namespace std;
 4 const int N = 55;
 5 int ne[N];
 6 
 7 char s[N],T[N];
 8 /*s为字串,T为主串*/
 9 int main(){
10     cin>>s+1;
11     int len = strlen(s+1);
12     for(int i = 2,j = 0;i <= len;++i){
13         while(j&&s[i] != s[j+1]) j = ne[j];
14         if(s[j+1] == s[i]){
15             j++;
16         }
17         ne[i] = j;
18     }/*next数组的构造*/
19     /*
20         整个过程在于对字串当前位置查看是否存在最长的前后缀匹配
21         当i等于2时,其前只包含1,
22         当i等于3时,此前只包含1,2
23         这里的next数组的含义是上一次匹配的最长前后缀的最后一位
24 */ 25 26 cin>>T+1; 27 int len2 = strlen(T+1); 28 for(int i = 1,j = 0;i <= len2;++i){ 29 while(j && T[i] != s[j+1]) j = ne[j]; 30 if(s[j+1] == T[i])j++; 31 if(j == len){ 32 cout<<i-strlen(s+1)+1<<endl; 33 j = ne[j]; 34 } 35 }/*匹配过程,如果主串中存在字串,则输出字串的初始位置*/ 36 37 return 0; 38 }

重点还是在对于字串的最长前后缀匹配的理解,next数组的构造可以多写两组数据自己模拟两遍就理解原理了

posted @ 2022-04-12 10:07  empty_y  阅读(37)  评论(0)    收藏  举报