-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path25_KMP.cpp
50 lines (45 loc) ยท 1.03 KB
/
25_KMP.cpp
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 <iostream>
#include <vector>
using namespace std;
vector<int> makeTable(string pattern){
int patternSize = pattern.size();
vector<int> table(patternSize, 0);
int j = 0;
for(int i=1;i<patternSize;i++){
while(j>0 && pattern[i]!=pattern[j]){
j = table[j-1];
}
if(pattern[i] == pattern[j]){
table[i] = ++j;
}
}
return table;
}
void KMP(string parent, string pattern){
vector<int> table = makeTable(pattern);
int parentSize = parent.size();
int patternSize = pattern.size();
int j=0;
for(int i=0;i<parentSize;i++){
while(j>0 && parent[i]!=pattern[j]){
j = table[j-1];
}
if(parent[i] == pattern[j]){
if(j == patternSize - 1){
printf("%d๋ฒ์งธ์์ ์ฐพ์์ต๋๋ค.\n",i-patternSize+2);
j=table[j];
}else{
j++;
}
}
}
}
int main(void){
string parent = "ababacabacaabacaaba";
string pattern = "abacaaba";
KMP(parent,pattern);
return 0;
}
// ์คํ๊ฒฐ๊ณผ
// 7๋ฒ์งธ์์ ์ฐพ์์ต๋๋ค.
// 12๋ฒ์งธ์์ ์ฐพ์์ต๋๋ค.