Python Find the Longest Common Substring of Two Strings
The longest common substring problem is: given two strings, find the longest substring common to both. A substring is a contiguous sequence of characters within a string. We can solve this problem using dynamic programming.
Example
def
longest_common_substring
(
s1
,
s2
)
:
m
=
len
(
s1
)
n
=
len
(
s2
)
Create a 2D array to store the length of the longest common substring
dp
=
[
[
0
]
(
n +
1
)
for
_
in
range
(
m +
1
)
]
max_length
=
0
Record the length of the longest common substring
end_pos
=
0
Record the ending position of the longest common substring
for
i
in
range
(
1
,
m +
1
)
:
for
j
in
range
(
1
,
n +
1
)
:
if
s1
[
i -
1
]
==
s2
[
j -
1
]
:
dp
[
i
]
[
j
]
=
dp
[
i -
1
]
[
j -
1
]
1
if
dp
[
i
]
[
j
]
max_length:
max_length
=
dp
[
i
]
[
j
]
end_pos
=
i
else
:
dp
[
i
]
[
j
]
=
0
Return the longest common substring
return
s1
[
end_pos - max_length:end_pos
]
Testing
s1
=
"abcdef"
s2
=
"zbcdf"
result
=
longest_common_substring
(
s1
,
s2
)
(
"The longest common substring is:"
,
result
)
Code analysis:
dpis a 2D array,dp[i][j]represents the strings1's firsticharacters and the strings2's firstjcharacters' longest common substring length.- We iterate over each character of the two strings; if
s1[i-1]ands2[j-1]are equal, thendp[i][j]'s value equalsdp[i-1][j-1] + 1, otherwisedp[i][j]is 0. max_lengthis used to record the length of the longest common substring,end_posis used to record the ending position of the longest common substring.- Finally, we use
s1[end_pos - max_length:end_pos]to obtain the longest common substring.
Output result:
最长公共子串是: bcd
Python3 Examples