|
| 1 | +""" |
| 2 | +Longest Common Substring Problem Statement: Given two sequences, find the |
| 3 | +longest common substring present in both of them. A substring is |
| 4 | +necessarily continuous. |
| 5 | +Example: "abcdef" and "xabded" have two longest common substrings, "ab" or "de". |
| 6 | +Therefore, algorithm should return any one of them. |
| 7 | +""" |
| 8 | + |
| 9 | + |
| 10 | +def longest_common_substring(text1: str, text2: str) -> str: |
| 11 | + """ |
| 12 | + Finds the longest common substring between two strings. |
| 13 | + >>> longest_common_substring("", "") |
| 14 | + '' |
| 15 | + >>> longest_common_substring("a","") |
| 16 | + '' |
| 17 | + >>> longest_common_substring("", "a") |
| 18 | + '' |
| 19 | + >>> longest_common_substring("a", "a") |
| 20 | + 'a' |
| 21 | + >>> longest_common_substring("abcdef", "bcd") |
| 22 | + 'bcd' |
| 23 | + >>> longest_common_substring("abcdef", "xabded") |
| 24 | + 'ab' |
| 25 | + >>> longest_common_substring("GeeksforGeeks", "GeeksQuiz") |
| 26 | + 'Geeks' |
| 27 | + >>> longest_common_substring("abcdxyz", "xyzabcd") |
| 28 | + 'abcd' |
| 29 | + >>> longest_common_substring("zxabcdezy", "yzabcdezx") |
| 30 | + 'abcdez' |
| 31 | + >>> longest_common_substring("OldSite:GeeksforGeeks.org", "NewSite:GeeksQuiz.com") |
| 32 | + 'Site:Geeks' |
| 33 | + >>> longest_common_substring(1, 1) |
| 34 | + Traceback (most recent call last): |
| 35 | + ... |
| 36 | + ValueError: longest_common_substring() takes two strings for inputs |
| 37 | + """ |
| 38 | + |
| 39 | + if not (isinstance(text1, str) and isinstance(text2, str)): |
| 40 | + raise ValueError("longest_common_substring() takes two strings for inputs") |
| 41 | + |
| 42 | + text1_length = len(text1) |
| 43 | + text2_length = len(text2) |
| 44 | + |
| 45 | + dp = [[0] * (text2_length + 1) for _ in range(text1_length + 1)] |
| 46 | + ans_index = 0 |
| 47 | + ans_length = 0 |
| 48 | + |
| 49 | + for i in range(1, text1_length + 1): |
| 50 | + for j in range(1, text2_length + 1): |
| 51 | + if text1[i - 1] == text2[j - 1]: |
| 52 | + dp[i][j] = 1 + dp[i - 1][j - 1] |
| 53 | + if dp[i][j] > ans_length: |
| 54 | + ans_index = i |
| 55 | + ans_length = dp[i][j] |
| 56 | + |
| 57 | + return text1[ans_index - ans_length : ans_index] |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == "__main__": |
| 61 | + import doctest |
| 62 | + |
| 63 | + doctest.testmod() |
0 commit comments