forked from sandeshghanta/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMP.cpp
More file actions
50 lines (50 loc) · 746 Bytes
/
KMP.cpp
File metadata and controls
50 lines (50 loc) · 746 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
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main(){
string n,m;
ll i,j,len;
cout << "Enter the string to be checked ";
cin >> n;
cout << "Enter the string to check for ";
cin >> m;
ll lps[m.size()];
lps[0] = 0;
len = 0;
//Building the LPS array
for (i=1;i<m.size();){
if (m[len] == m[i]){
len++;
lps[i] = len;
i++;
}
else{
if (len != 0){
len = lps[len-1];
}
else{
lps[i] = 0;
i++;
}
}
}
j = 0;
for (i=0;i<n.size();){
if (n[i] == m[j]){
j++;
i++;
if (j == m.size()){
cout << "Found " << m << " from index " << i - j << " to " << i - 1 << endl;
j = lps[j-1];
}
}
else{
if (j != 0){
j = lps[j-1];
}
else{
i++;
}
}
}
}