-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBMGoodSuffix.cpp
More file actions
100 lines (83 loc) · 1.73 KB
/
Copy pathBMGoodSuffix.cpp
File metadata and controls
100 lines (83 loc) · 1.73 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <bits/stdc++.h>
using namespace std;
void preprocess_strong_suffix(int *shift, int *bpos, string pat, int m)
{
int i = m, j = m + 1;
bpos[i] = j;
while (i > 0)
{
while (j <= m && pat[i - 1] != pat[j - 1])
{
if (shift[j] == 0)
{
shift[j] = j - i;
}
j = bpos[j];
}
i--;
j--;
bpos[i] = j;
}
}
void preprocess_case2(int *shift, int *bpos, string pat, int m)
{
int i, j;
j = bpos[0];
for (i = 0; i <= m; i++)
{
if (shift[i] == 0)
{
shift[i] = j;
}
if (i == j)
{
j = bpos[j];
}
}
}
void search(string text, string pat)
{
int s = 0, j;
int m = pat.length();
int n = text.length();
int bpos[m + 1], shift[m + 1];
for (int i = 0; i < m + 1; i++)
{
shift[i] = 0;
}
preprocess_strong_suffix(shift, bpos, pat, m);
preprocess_case2(shift, bpos, pat, m);
while (s <= n - m)
{
j = m - 1;
while (j >= 0 && pat[j] == text[s + j])
{
j--;
}
if (j < 0)
{
cout << "\nPattern occurs at index: " << s;
s += shift[0];
}
else
{
s += shift[j + 1];
}
}
}
int main()
{
string txt = "AABAACAADAABAAABAA";
string pat = "AABA";
search(txt, pat);
return 0;
}
/*
Output:
Enter Text: AABAACAADAABAABA
Enter pattern: AABA
Using case 1 shifting is performed from index 3 to 10
Pattern occurs at index: 0
Pattern occurs at index: 9
Pattern occurs at index: 12
*/