-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstringMatching.cpp
More file actions
61 lines (45 loc) · 1.03 KB
/
stringMatching.cpp
File metadata and controls
61 lines (45 loc) · 1.03 KB
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
59
60
61
#include <bits/stdc++.h>
using namespace std;
#define MAXN 100010
char T[MAXN], P[MAXN]; // T = string, P = pattern
int b[MAXN], n, m; // b = back table, n = size of string, m = size of pattern
void kmpPreprocess() {
int i = 0, j = -1;
b[0] = -1;
while(i < m) {
while(j >= 0 && P[i] != P[j]) {
j = b[j];
}
i++; j++;
b[i] = j;
}
}
void kmpSearch() {
int i = 0, j = 0;
while(i < n) {
while(j >= 0 && T[i] != P[j]) {
j = b[j];
}
i++; j++;
if(j == m) {
printf("P is found at index %d in T\n", i-j);
j = b[j];
}
}
}
int main() {
string line;
getline(cin, line);
for(int i = 0; i < (int)line.size(); ++i) {
T[i] = line[i];
}
getline(cin, line);
for(int i = 0; i < (int)line.size(); ++i) {
P[i] = line[i];
}
n = strlen(T);
m = strlen(P);
kmpPreprocess();
kmpSearch();
return 0;
}