-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathKMP.cpp
More file actions
58 lines (54 loc) · 959 Bytes
/
KMP.cpp
File metadata and controls
58 lines (54 loc) · 959 Bytes
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
/// KMP
/// Time complexity O(N + M)
/// Coded By Raihan Chowdhury
/// Department of CSE , IIUC
/// Team IIUC_(GR)^2
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
ll prefix[100001];
void setPrefix (string s)
{
int i = 0 ,j = -1;
int len = s.length();
prefix[0] = -1;
while(i < len)
{
while( j >= 0 && s[i] != s[j])
{
j = prefix[j];
}
i++;
j++;
prefix[i] = j;
}
}
bool kmp_algorithm(string s , string s1)
{
int n = s.length();
int m = s1.length();
int i = 0 , j = 0;
setPrefix(s1);
int c = 0;
while(i < n)
{
while(j >= 0 and s[i] != s1[j])
{
j = prefix[j];
}
i++;
j++;
if(j == m)
{
return true;
}
}
return false;
}
int main()
{
string s1 = "abcdefg";
string s2 = "dek";
bool x = kmp_algorithm(s1,s2);
cout<<x<< endl;
}