TheAlgorithms-Python
64 строки · 1.6 Кб
1"""
2https://cp-algorithms.com/string/prefix-function.html
3
4Prefix function Knuth–Morris–Pratt algorithm
5
6Different algorithm than Knuth-Morris-Pratt pattern finding
7
8E.x. Finding longest prefix which is also suffix
9
10Time Complexity: O(n) - where n is the length of the string
11"""
12
13
14def prefix_function(input_string: str) -> list:
15"""
16For the given string this function computes value for each index(i),
17which represents the longest coincidence of prefix and suffix
18for given substring (input_str[0...i])
19
20For the value of the first element the algorithm always returns 0
21
22>>> prefix_function("aabcdaabc")
23[0, 1, 0, 0, 0, 1, 2, 3, 4]
24>>> prefix_function("asdasdad")
25[0, 0, 0, 1, 2, 3, 4, 0]
26"""
27
28# list for the result values
29prefix_result = [0] * len(input_string)
30
31for i in range(1, len(input_string)):
32# use last results for better performance - dynamic programming
33j = prefix_result[i - 1]
34while j > 0 and input_string[i] != input_string[j]:
35j = prefix_result[j - 1]
36
37if input_string[i] == input_string[j]:
38j += 1
39prefix_result[i] = j
40
41return prefix_result
42
43
44def longest_prefix(input_str: str) -> int:
45"""
46Prefix-function use case
47Finding longest prefix which is suffix as well
48
49>>> longest_prefix("aabcdaabc")
504
51>>> longest_prefix("asdasdad")
524
53>>> longest_prefix("abcab")
542
55"""
56
57# just returning maximum value of the array gives us answer
58return max(prefix_function(input_str))
59
60
61if __name__ == "__main__":
62import doctest
63
64doctest.testmod()
65