-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
50 lines (44 loc) · 1.01 KB
/
Copy pathmain.cpp
File metadata and controls
50 lines (44 loc) · 1.01 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
#include <bits/stdc++.h>
using namespace std;
void prefix_table(string pattern, int prefix[], int n) {
prefix[1] = 0;
int len = 0;
int i = 1;
while (i <= n) {
if (pattern[i] == pattern[len]) {
len++;
prefix[i + 1] = len;
i++;
} else {
if (len > 1) {
len = prefix[len];
} else {
prefix[i + 1] = len;
i++;
}
}
}
}
int main() {
string pattern = "ABABCABAA";
string text = "AIUJDGABABABCABAA";
int prefix[10];
int n = 9, i = 0, j = 0;
prefix[0] = -1;
prefix_table(pattern, prefix, n);
while (i < text.size()) {
if (j == n - 1 && text[i] == pattern[j]){
printf("Found pattern at %d\n",i-j);
j = prefix[j];
}
if(text[i] == pattern[j]){
i++;j++;
}else{
j = prefix[j];
if(j == -1){
i++;j++;
}
}
}
return 0;
}