-
Notifications
You must be signed in to change notification settings - Fork 0
/
KMP.cpp
47 lines (47 loc) · 795 Bytes
/
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
#include <iostream>
#include<cstring>
using namespace std;
int Next[1000005];
string T,M;
void getNext()
{
int i=1,j=0;
while(i<T.length())
{
if(j==0||T[i-1]==T[j-1])
{
i++;
j++;
if (T[i-1]!=T[j-1]) Next[i] = j;
else Next[i]= Next[j];
}
else j=Next[j];
}
}
int main(int, char**){
cin>>M>>T;
bool flag;
int lenT=T.length();
getNext();
int i=1,j=1;
while(i<=M.length())
{
if(j==0||M[i-1]==T[j-1])
{
i++;
j++;
}
else
{
j=Next[j];
}
if(j>T.length())
{
flag=1;
break;
}
}
if(flag==1) cout<<"YES";
else cout<<"NO";
return 0;
}