📅  最后修改于: 2023-12-03 15:28:41.074000             🧑  作者: Mango
This problem requires the implementation of a program that computes the longest common substring of two given strings. The program should take two strings as input and return the longest common substring, along with its length.
Given two strings X
and Y
, the objective is to find the longest common substring between them. A substring is a contiguous sequence of characters that occurs within a string. The common substring is a substring that occurs in both strings.
For example, given the strings X = "ABCD"
and Y = "BCDF"
, the longest common substring is "BC"
, which has a length of 2
.
The problem can be solved by using dynamic programming approach. We can create a two-dimensional matrix T
of dimensions (m+1) x (n+1)
, where m
and n
are the lengths of strings X
and Y
, respectively. The value at T[i][j]
represents the length of the longest common suffix of X[0:i]
and Y[0:j]
.
The algorithm for filling up the matrix T
is as follows:
i
in 1 to m
:j
in 1 to n
:X[i] == Y[j]
, then T[i][j] = T[i-1][j-1] + 1
T[i][j] = 0
The above algorithm populates the matrix T
in a bottom-up manner. The longest common substring can then be obtained by finding the maximum value in the matrix T
and tracing back to its origin.
Here is an implementation of the above approach in Python:
def longest_common_substring(X, Y):
m, n = len(X), len(Y)
T = [[0] * (n+1) for _ in range(m+1)]
longest_len = 0
longest_end = 0
for i in range(1, m+1):
for j in range(1, n+1):
if X[i-1] == Y[j-1]:
T[i][j] = T[i-1][j-1] + 1
if T[i][j] > longest_len:
longest_len = T[i][j]
longest_end = i
else:
T[i][j] = 0
longest_start = longest_end - longest_len
return X[longest_start:longest_end], longest_len
The function longest_common_substring
takes two strings X
and Y
as input and returns a tuple (substring, length)
where substring
is the longest common substring and length
is its length.
In conclusion, we have discussed the problem of finding the longest common substring between two given strings and presented a dynamic programming approach to solve it. The provided code snippet can serve as a starting point for further implementation and optimization.