-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathkmp.cpp
More file actions
executable file
·91 lines (88 loc) · 1.81 KB
/
kmp.cpp
File metadata and controls
executable file
·91 lines (88 loc) · 1.81 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
typedef long double ld;
#define MOD 1000000007
#define INF 1000000000000000000
#define endll "\n"
#define pb push_back
#define forn(i,n) for(i=0;i<n;i++)
#define forab(i,a,b) for(i=a;i<=b;i++)
#define vpll vector<pair<ll,ll>>
#define pll pair<ll,ll>
#define vll vector<ll>
#define ff first
#define ss second
#define bs binary_search
#define lb lower_bound
#define ub upper_bound
#define test ll t;cin>>t; while(t--)
#define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
void createLPS(string pattern,ll m,ll *lps)
{
ll len=0; //length of the previous longest prefix which is also a suffix
lps[0]=0;
ll i=1;
while(i<m)
{
if(pattern[i]==pattern[len])
{
len++;
lps[i]=len;
i++;
}
else
{
if(len!=0)
{
len=lps[len - 1];
}
else
{
lps[i]=0;
i++;
}
}
}
}
void KMP(string pattern,string text,ll n,ll m)
{
ll i=0,j=0;
ll lps[m];
createLPS(pattern,m,lps);
while(i<n)
{
if(pattern[j]==text[i])
{
i++;
j++;
}
if(j==m)
{
cout<<i-j<<" ";
j=lps[j-1];
}
else
if(i<n && pattern[j]!=text[i])
{
if(j!=0)
j=lps[j-1];
else
i++;
}
}
}
int main()
{
fast_io;
string text,pattern;
cin>>pattern>>text;
ll n=text.length();
ll m=pattern.length();
if(m>n)
cout<<endl;
else
KMP(pattern,text,n,m);
return 0;
}