KMP算法(查找该字串是否存在)

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <stdlib.h>
 5 #include <algorithm>
 6 #include <math.h>
 7 #include <vector>
 8 #include <list>
 9 #include <map>
10 #include <set>
11 using namespace std;
12 
13 char chsum[100002],ch[100002],x[200004];
14 int lowbit[100002];
15 
16 void kmp()
17 {
18     lowbit[0]=-1;
19     lowbit[1]=0;
20     int k=0,j=1;
21     while(j<strlen(ch))
22     {
23         if(k==-1||ch[k]==ch[j])
24         {
25             lowbit[++j]=++k;
26         }
27         else
28         {
29             k=lowbit[k];
30         }
31     }
32 }
33 
34 bool KMP_Index()  
35 {  
36     int i = 0, j = 0;
37     int slen=strlen(chsum);
38     int tlen=strlen(ch);
39     kmp(); 
40     while(i < slen && j < tlen)  
41     {  
42         if(j == -1 || chsum[i] == ch[j])  
43         {  
44             i++; j++;  
45         }  
46         else  
47             j = lowbit[j];
48         if(j==tlen) return true;  
49     }  
50     if(j == strlen(ch))  
51         return true;  
52     else  
53         return false;  
54 }
55 
56 int main()
57 {
58     while(~scanf("%s",x)){
59         strcpy(chsum,x);
60         strcat(chsum,x);
61         scanf("%s",ch);
62         memset(lowbit,0,sizeof(lowbit));
63         if(strlen(x)<strlen(ch)) cout<<"no"<<endl;
64         else{
65             if(KMP_Index()) cout<<"yes"<<endl;
66             else cout<<"no"<<endl;
67         }
68     }
69 }

 

转载于:https://www.cnblogs.com/Culion-BEAR/p/8818903.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值