For the given string this function computes value for each index(i), which represents the longest coincidence of prefix and suffix for given substring (input_str[0...i]) For the value of the first element the algorithm always returns 0 >>> prefix_function("aabcdaabc") [0,
(input_string: str)
| 12 | |
| 13 | |
| 14 | def prefix_function(input_string: str) -> list: |
| 15 | """ |
| 16 | For the given string this function computes value for each index(i), |
| 17 | which represents the longest coincidence of prefix and suffix |
| 18 | for given substring (input_str[0...i]) |
| 19 | |
| 20 | For 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 |
| 29 | prefix_result = [0] * len(input_string) |
| 30 | |
| 31 | for i in range(1, len(input_string)): |
| 32 | # use last results for better performance - dynamic programming |
| 33 | j = prefix_result[i - 1] |
| 34 | while j > 0 and input_string[i] != input_string[j]: |
| 35 | j = prefix_result[j - 1] |
| 36 | |
| 37 | if input_string[i] == input_string[j]: |
| 38 | j += 1 |
| 39 | prefix_result[i] = j |
| 40 | |
| 41 | return prefix_result |
| 42 | |
| 43 | |
| 44 | def longest_prefix(input_str: str) -> int: |