1
1
def string_matching_naive (text = '' , pattern = '' ):
2
2
"""Returns positions where pattern is found in text.
3
3
4
- We slide the string to match 'pattern' over the text
4
+ Sliding window.
5
5
6
6
O((n-m)m)
7
7
Example: text = 'ababbababa', pattern = 'aba'
@@ -24,6 +24,11 @@ def string_matching_naive(text='', pattern=''):
24
24
def string_matching_rabin_karp (text = '' , pattern = '' , hash_base = 256 ):
25
25
"""Returns positions where pattern is found in text.
26
26
27
+ Similar to the naive approach but matches the hash value of the pattern
28
+ with the hash value of current substring of text. Needs to match
29
+ individual characters once a match is found because of potential
30
+ hash collisions.
31
+
27
32
worst case: O(nm)
28
33
O(n+m) if the number of valid matches is small and the pattern is large.
29
34
@@ -75,6 +80,8 @@ def hash_value(s, base):
75
80
def string_matching_knuth_morris_pratt (text = '' , pattern = '' ):
76
81
"""Returns positions where pattern is found in text.
77
82
83
+ https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
84
+
78
85
O(m+n)
79
86
Example: text = 'ababbababa', pattern = 'aba'
80
87
string_matching_knuth_morris_pratt(text, pattern) returns [0, 5, 7]
@@ -115,6 +122,8 @@ def compute_prefix_function(p):
115
122
def string_matching_boyer_moore_horspool (text = '' , pattern = '' ):
116
123
"""Returns positions where pattern is found in text.
117
124
125
+ https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm
126
+
118
127
O(n)
119
128
Performance: ord() is slow so we shouldn't use it here
120
129
0 commit comments