Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7a553e9

Browse files
committed
Added KMP Algorithm
1 parent fe61cb7 commit 7a553e9

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

‎src/KMP.cpp

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#include <iostream>
2+
#include<bits/stdc++.h>
3+
using namespace std;
4+
5+
/*
6+
* get prefix list
7+
*/
8+
vector<int> computePrefix(string str) {
9+
10+
int m=int(str.length());
11+
vector<int> prefix(m);
12+
for(int i=1,k=0;i<m;++i)
13+
{
14+
if(k>0&&str[i]!=str[k])
15+
k=prefix[k-1];
16+
if(str[k]==str[i])
17+
prefix[i]=++k;
18+
else
19+
prefix[i]=k;
20+
}
21+
22+
return prefix;
23+
}
24+
25+
void KMP(string &str, string pat) {
26+
int m = int(str.length());
27+
int n = int(pat.length());
28+
vector<int> longestPrefix = computePrefix(pat);
29+
30+
for (int i = 0, k = 0; i < m; ++i) {
31+
if (k > 0 && pat[k] != str[i])
32+
k = longestPrefix[k - 1];
33+
if (str[i] == pat[k])
34+
++k;
35+
if (k == n) {
36+
cout << i - n + 1 << "\n";
37+
//more than one pattern
38+
k = longestPrefix[k - 1];
39+
}
40+
41+
}
42+
}
43+
44+
int main() {
45+
string s,p;
46+
cin>>s>>p;
47+
KMP(s,p);
48+
return 0;
49+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /