forked from CodeToExpress/dailycodebase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KMP.cpp
67 lines (66 loc) · 1.02 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
66
67
/**
* @date 04/01/19
* @author SPREEHA DUTTA
*/
#include <bits/stdc++.h>
using namespace std;
void calc(string w,int m,int p[])
{
int l=0,i=1;p[0]=0;
while(i<m)
{
if(p[i]==p[l])
{
l++;
p[i]=l;
i++;
}
else
{
if(l!=0)
l=p[l-1];
else
{
p[i]=l;
i++;
}
}
}
}
int search(string s,string w)
{
int i=0,j=0;int k=-1;
int m=w.length();
int n=s.length();
int arr[m];
calc(w,m,arr);
while(i<n)
{
if(w[j]==s[i])
{
j++;
i++;
}
if(j==m)
{
k=i-j;
break;
}
else if(i<n && w[j]!=s[i])
{
if(j!=0)
j=arr[j-1];
else
i++;
}
}
return k;
}
int main()
{
string s,w;
getline(cin,s);
getline(cin,w);
int t=search (w,s);
cout<<"\n"<<t<<endl;
}