Skip to content

Commit efa06d8

Browse files
akshat2412nimit95
authored andcommitted
added KMP (CodersForLife#138)
* added KMP algorithm * added Tries DS * Revert "added Tries DS" This reverts commit a977d32.
1 parent a6ddd5c commit efa06d8

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

String Matching/KMP.cpp

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
void make_lps(int *lps, string &pattern){
5+
int j=0, i=1;
6+
lps[0]=0;
7+
while(i<pattern.length()){
8+
if(pattern[i]==pattern[j]){
9+
lps[i++]=(j++)+1;
10+
}
11+
else if(j>0){
12+
j=lps[j-1];
13+
}
14+
else{
15+
lps[i++]=0;
16+
}
17+
}
18+
}
19+
20+
int match(string &orig, string &pattern, int *lps){
21+
int patt_index=0;
22+
int orig_index=0;
23+
while(orig_index<orig.length()){
24+
if(orig[orig_index]==pattern[patt_index]){
25+
orig_index++;
26+
patt_index++;
27+
}
28+
else if(patt_index==0){
29+
orig_index++;
30+
}
31+
else{
32+
patt_index=lps[patt_index-1];
33+
}
34+
if(patt_index==pattern.length()){
35+
return 1;
36+
}
37+
}
38+
return patt_index==pattern.length();
39+
}
40+
41+
int main()
42+
{
43+
// freopen("input.txt", "rd", stdin);
44+
string orig;
45+
cin>>orig;
46+
47+
string pattern;
48+
cin>>pattern;
49+
int lps[pattern.length()];
50+
make_lps(lps, pattern);
51+
52+
53+
cout<<endl<<match(orig, pattern, lps);
54+
return 0;
55+
}

String Matching\KMP

13.4 KB
Binary file not shown.

0 commit comments

Comments
 (0)