📅  最后修改于: 2023-12-03 15:12:37.953000             🧑  作者: Mango
This problem is a dynamic programming problem that requires finding the length of the longest common subsequence (LCS) between two given strings. The strings are provided in the input, and the program needs to output the length of the LCS.
Given two strings s1 and s2, write a program to find the length of the longest common subsequence (LCS).
Input:
s1: "ABCDGH"
s2: "AEDFHR"
Output:
3
Explanation:
The longest common subsequence is "ADH", which has a length of 3.
The dynamic programming approach to solve this problem is well known. We need to create a table of size (m + 1) x (n + 1), where m and n are the lengths of the two given strings, and initialize all values to 0.
Then, we fill in the table row by row, from left to right, using the following recurrence relation:
if s1[i-1] == s2[j-1]:
LCS[i][j] = 1 + LCS[i-1][j-1]
else:
LCS[i][j] = max(LCS[i-1][j], LCS[i][j-1])
Here, LCS[i][j] refers to the length of the LCS of the substrings s1[0:i] and s2[0:j]. If the two characters are the same, we add 1 to the length of the LCS of the shorter substrings we already know about (i.e. s1[0:i-1] and s2[0:j-1]). If not, we take the max value of LCS[i-1][j] and LCS[i][j-1], which represents the LCS of the substrings obtained by removing one character from each of the two original substrings.
The final answer is stored in the bottom right corner of the table, LCS[m][n].
def lcs(s1: str, s2: str) -> int:
m, n = len(s1), len(s2)
lcs_table = [[0] * (n+1) for _ in range(m+1)]
for i in range(1, m+1):
for j in range(1, n+1):
if s1[i-1] == s2[j-1]:
lcs_table[i][j] = 1 + lcs_table[i-1][j-1]
else:
lcs_table[i][j] = max(lcs_table[i-1][j], lcs_table[i][j-1])
return lcs_table[m][n]
# Example usage
s1, s2 = "ABCDGH", "AEDFHR"
print(lcs(s1, s2)) # Output: 3
This code snippet implements the dynamic programming approach explained above, using Python as the programming language. It defines a function lcs
that takes in two strings s1 and s2 and returns the length of their LCS. It works for any two input strings provided in the expected format.