模板——KMP算法

关于子串的查找

 1 char a[maxn],b[maxn];
 2 int lena,lenb,net[maxn];
 3 void getnet() { ///得到next数组
 4     lenb=strlen(b);
 5     net[0]=-1;
 6     int i=0,j=-1;
 7     while(i<lenb) {
 8         if(j==-1||b[i]==b[j])
 9             net[++i]=++j;
10         else j=net[j];
11     }
12     return ;
13 }
14 int getans() {  ///KMP查找b串在a中的出现次数
15     lena=strlen(a);
16     lenb=strlen(b);
17     int ans=0;
18     if(lena==lenb&&lena==1) {
19         if(a[0]==b[0]) return 1;
20         else return 0;
21     }
22     for(int i=0,j=0;i<lena;i++) {
23         while(j>0&&a[i]!=b[j]) j=net[j];
24         if(a[i]==b[j]) ++j;
25         if(j==lenb) ans++,j=net[j];
26     }
27     return ans;
28 }
View Code

猜你喜欢

转载自www.cnblogs.com/wuliking/p/11601257.html