This action will force synchronization from 编程语言算法集/Python, which will overwrite any changes that you have made since you forked the repository, and can not be recovered!!!
Synchronous operation will process in the background and will refresh the page when finishing processing. Please be patient.
"""https://cp-algorithms.com/string/prefix-function.htmlPrefix function Knuth–Morris–Pratt algorithmDifferent algorithm than Knuth-Morris-Pratt pattern findingE.x. Finding longest prefix which is also suffixTime Complexity: O(n) - where n is the length of the string"""def prefix_function(input_string: str) -> list:"""For the given string this function computes value for each index(i),which represents the longest coincidence of prefix and suffixfor given substring (input_str[0...i])For the value of the first element the algorithm always returns 0>>> prefix_function("aabcdaabc")[0, 1, 0, 0, 0, 1, 2, 3, 4]>>> prefix_function("asdasdad")[0, 0, 0, 1, 2, 3, 4, 0]"""# list for the result valuesprefix_result = [0] * len(input_string)for i in range(1, len(input_string)):# use last results for better performance - dynamic programmingj = prefix_result[i - 1]while j > 0 and input_string[i] != input_string[j]:j = prefix_result[j - 1]if input_string[i] == input_string[j]:j += 1prefix_result[i] = jreturn prefix_resultdef longest_prefix(input_str: str) -> int:"""Prefix-function use caseFinding longest prefix which is suffix as well>>> longest_prefix("aabcdaabc")4>>> longest_prefix("asdasdad")4>>> longest_prefix("abcab")2"""# just returning maximum value of the array gives us answerreturn max(prefix_function(input_str))if __name__ == "__main__":import doctestdoctest.testmod()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。