Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 51k
Expand file tree
/
Copy pathlongest_common_substring.py
More file actions
Latest commit
70 lines (57 loc) · 2 KB
/
Copy pathlongest_common_substring.py
File metadata and controls
70 lines (57 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""
Longest Common Substring Problem Statement:
Given two sequences, find the
longest common substring present in both of them. A substring is
necessarily continuous.
Example:
``abcdef`` and ``xabded`` have two longest common substrings, ``ab`` or ``de``.
Therefore, algorithm should return any one of them.
"""
deflongest_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
"""
ifnot (isinstance(text1, str) andisinstance(text2, str)):
raiseValueError("longest_common_substring() takes two strings for inputs")
ifnottext1ornottext2:
return""
text1_length=len(text1)
text2_length=len(text2)
dp= [[0] * (text2_length+1) for_inrange(text1_length+1)]
end_pos=0
max_length=0
foriinrange(1, text1_length+1):
forjinrange(1, text2_length+1):
iftext1[i-1] ==text2[j-1]:
dp[i][j] =1+dp[i-1][j-1]
ifdp[i][j] >max_length:
end_pos=i
max_length=dp[i][j]
returntext1[end_pos-max_length : end_pos]
if__name__=="__main__":
importdoctest
doctest.testmod()