-
Notifications
You must be signed in to change notification settings - Fork 13
/
KMP.cpp
65 lines (41 loc) · 2.16 KB
/
KMP.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;
int main()
{
int m;
while(scanf("%d",&m)!=EOF)
{
string p;
string s;
bool flag=0;
cin>>p>>s;
int pre[m];
int k=-1;
pre[0]=k;
for(int q=1;q<=m-1;q++)
{
while(k>-1 && p[k+1]!=p[q])
k=pre[k];
if(p[k+1]==p[q])
k=k+1;
pre[q]=k;
}
int n=s.length();
int q=-1;
for(int i=0;i<n;i++)
{
while(q>-1 && p[q+1]!=s[i])
q=pre[q];
if(p[q+1]==s[i])
q=q+1;
if(q==m-1)
printf("%d\n",(i-m+1)),q=pre[q],flag=1;
}
if(!flag)
printf("\n\n");
}
system ("pause");
return 0;
}