同步操作将从 编程语言算法集/Python 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
"""Longest Common Substring Problem Statement: Given two sequences, find thelongest common substring present in both of them. A substring isnecessarily continuous.Example: "abcdef" and "xabded" have two longest common substrings, "ab" or "de".Therefore, algorithm should return any one of them."""def longest_common_substring(text1: str, text2: str) -> str:"""Finds the longest common substring between two strings.>>> longest_common_substring("", "")''>>> longest_common_substring("a","")''>>> longest_common_substring("", "a")''>>> longest_common_substring("a", "a")'a'>>> longest_common_substring("abcdef", "bcd")'bcd'>>> longest_common_substring("abcdef", "xabded")'ab'>>> longest_common_substring("GeeksforGeeks", "GeeksQuiz")'Geeks'>>> longest_common_substring("abcdxyz", "xyzabcd")'abcd'>>> longest_common_substring("zxabcdezy", "yzabcdezx")'abcdez'>>> longest_common_substring("OldSite:GeeksforGeeks.org", "NewSite:GeeksQuiz.com")'Site:Geeks'>>> longest_common_substring(1, 1)Traceback (most recent call last):...ValueError: longest_common_substring() takes two strings for inputs"""if not (isinstance(text1, str) and isinstance(text2, str)):raise ValueError("longest_common_substring() takes two strings for inputs")text1_length = len(text1)text2_length = len(text2)dp = [[0] * (text2_length + 1) for _ in range(text1_length + 1)]ans_index = 0ans_length = 0for i in range(1, text1_length + 1):for j in range(1, text2_length + 1):if text1[i - 1] == text2[j - 1]:dp[i][j] = 1 + dp[i - 1][j - 1]if dp[i][j] > ans_length:ans_index = ians_length = dp[i][j]return text1[ans_index - ans_length : ans_index]if __name__ == "__main__":import doctestdoctest.testmod()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。