Skip to content

Commit 8de8136

Browse files
committed
refactor(strings): Improve KMP implementation and tests
1 parent 0a2ed73 commit 8de8136

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed

strings/knuth_morris_pratt.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
This results in an optimal time complexity of O(n + m), where n is the length
99
of the text and m is the length of the pattern.
1010
11-
Source: https://en.wikipedia.org/wiki/KnuthMorrisPratt_algorithm
11+
Source: https://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm
1212
"""
1313
from __future__ import annotations
1414

@@ -45,12 +45,11 @@ def _compute_lps_array(pattern: str) -> list[int]:
4545
length += 1
4646
lps[i] = length
4747
i += 1
48+
elif length != 0:
49+
length = lps[length - 1]
4850
else:
49-
if length != 0:
50-
length = lps[length - 1]
51-
else:
52-
lps[i] = 0
53-
i += 1
51+
lps[i] = 0
52+
i += 1
5453
return lps
5554

5655

@@ -119,4 +118,4 @@ def knuth_morris_pratt_search(text: str, pattern: str) -> list[int]:
119118
if __name__ == "__main__":
120119
import doctest
121120

122-
doctest.testmod()
121+
doctest.testmod()

0 commit comments

Comments
 (0)