KMP模板

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 /* P 为模式串,下标从 0 开始 */
 5 void GetNext(string P,int next[]){
 6     int p_len=P.size();
 7     int i=0;   // P 的下标
 8     int j=-1;
 9     next[0]=-1;
10 
11     while(i<p_len-1){
12         if (j == -1 || P[i] == P[j]){
13             i++;
14             j++;
15             next[i]=j;
16         }
17         else
18             j=next[j];
19     }
20 }
21 
22 /* 在 S 中找到 P 第一次出现的位置 */
23 int KMP(string S,string P,int next[]){
24     GetNext(P, next);
25     int i=0;  // S 的下标
26     int j=0;  // P 的下标
27     int s_len=S.size();
28     int p_len=P.size();
29     while (i<s_len&&j<p_len){
30         if (j==-1||S[i]==P[j]){  // P 的第一个字符不匹配或 S[i] == P[j]
31             i++;
32             j++;
33         }
34         else
35             j=next[j];  // 当前字符匹配失败,进行跳转
36     }
37 
38     if (j==p_len)  // 匹配成功
39         return i-j;
40 
41     return -1;
42 }
43 
44 int main(){
45     int n;
46     int next[10000]={0};
47     char a[10000],b[10000];
48     cin>>a;
49     cin>>b;
50     if(KMP(a,b,next)==0){
51         cout<<"yes\n";
52     }
53     else cout<<"no\n";
54     return 0;
55 }

 

转载于:https://www.cnblogs.com/Never-Land/p/10821852.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值