Skip to content

Commit 3edbb25

Browse files
committed
Add comments to string matching algos.
1 parent da6018e commit 3edbb25

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

algorithms/string.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
def string_matching_naive(text='', pattern=''):
22
"""Returns positions where pattern is found in text.
33
4-
We slide the string to match 'pattern' over the text
4+
Sliding window.
55
66
O((n-m)m)
77
Example: text = 'ababbababa', pattern = 'aba'
@@ -24,6 +24,11 @@ def string_matching_naive(text='', pattern=''):
2424
def string_matching_rabin_karp(text='', pattern='', hash_base=256):
2525
"""Returns positions where pattern is found in text.
2626
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+
2732
worst case: O(nm)
2833
O(n+m) if the number of valid matches is small and the pattern is large.
2934
@@ -75,6 +80,8 @@ def hash_value(s, base):
7580
def string_matching_knuth_morris_pratt(text='', pattern=''):
7681
"""Returns positions where pattern is found in text.
7782
83+
https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
84+
7885
O(m+n)
7986
Example: text = 'ababbababa', pattern = 'aba'
8087
string_matching_knuth_morris_pratt(text, pattern) returns [0, 5, 7]
@@ -115,6 +122,8 @@ def compute_prefix_function(p):
115122
def string_matching_boyer_moore_horspool(text='', pattern=''):
116123
"""Returns positions where pattern is found in text.
117124
125+
https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm
126+
118127
O(n)
119128
Performance: ord() is slow so we shouldn't use it here
120129

0 commit comments

Comments
 (0)