-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkmp_algorithm.py
86 lines (70 loc) · 2.4 KB
/
kmp_algorithm.py
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
class KMP:
"""Implementation of Knuth-Morris-Pratt string matching algorithm"""
@staticmethod
def compute_lps(pattern):
"""
Compute Longest Proper Prefix which is also Suffix array
Args:
pattern: Pattern string
Returns:
list: LPS array
"""
length = 0 # Length of previous longest prefix suffix
lps = [0] * len(pattern)
i = 1
while i < len(pattern):
if pattern[i] == pattern[length]:
length += 1
lps[i] = length
i += 1
else:
if length != 0:
length = lps[length - 1]
else:
lps[i] = 0
i += 1
return lps
@staticmethod
def search(text, pattern):
"""
Search for pattern in text using KMP algorithm
Args:
text: Text string to search in
pattern: Pattern to search for
Returns:
list: All positions where pattern occurs in text
"""
if not pattern or not text:
return []
# Compute LPS array
lps = KMP.compute_lps(pattern)
positions = []
i = j = 0 # i for text, j for pattern
while i < len(text):
if pattern[j] == text[i]:
i += 1
j += 1
if j == len(pattern):
positions.append(i - j)
j = lps[j - 1]
elif i < len(text) and pattern[j] != text[i]:
if j != 0:
j = lps[j - 1]
else:
i += 1
return positions
# Test implementation
if __name__ == "__main__":
# Test cases
test_cases = [
("ABABDABACDABABCABAB", "ABABCABAB"),
("AAAAAAAAA", "AAA"),
("ABCDEFGHIJK", "DEF"),
("Hello, World!", "World")
]
for text, pattern in test_cases:
positions = KMP.search(text, pattern)
if positions:
print(f"Pattern '{pattern}' found in '{text}' at positions: {positions}")
else:
print(f"Pattern '{pattern}' not found in '{text}'")