forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoyer_Moore.py
More file actions
37 lines (28 loc) · 707 Bytes
/
Boyer_Moore.py
File metadata and controls
37 lines (28 loc) · 707 Bytes
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
badchar = []
def badCharHeuristic(ch, size):
global badchar
for i in range(256):
badchar.append(-1)
for i in range(size):
badchar[ord(ch[i])] = i
def search(text, pattern):
global badchar
len_text = len(text)
len_pattern = len(pattern)
badCharHeuristic(pattern, len_pattern)
s = 0
while s < (len_text - len_pattern):
j = len_pattern - 1
while (j >= 0 and pattern[j] == text[s + j]):
j -= 1
if j < 0:
print("Pattern match at shift = {0}".format(s))
if (s + len_pattern < len_text):
s += len_pattern - badchar[ord(text[s + len_pattern])]
else:
s += 1
else:
s += max(1, j - badchar[ord(text[s + j])])
text = "ABAAABCD"
pattern = "ABC"
search(text, pattern)