Given two strings, find the longest common subsequence (LCS).
Your code should return the length of LCS.
Have you met this question in a real interview? Yes
Problem Correction
What's the definition of Longest Common Subsequence?
For "ABCD"
and "EDCA"
, the LCS is "A"
(or "D"
, "C"
), return 1
.
For "ABCD"
and "EACB"
, the LCS is "AC"
, return 2
.
lintcode:链接
最长公共子串:链接
参考链接:动态规划
dp数组为(m+1)*(n+1),dp[i][j]代表的是A数组前i个数(不包括i)和B数组前j个数(不包括j)的最长公共子序列
class Solution:
"""
@param A: A string
@param B: A string
@return: The length of longest common subsequence of A and B
"""
def longestCommonSubsequence(self, A, B):
# write your code here
m, n = len(A), len(B)
# 这样做的目的是避开0的位置
# dp[i][j]代表的是A数组前i个数(不包括i)和B数组前j个数(不包括j)的最长公共子序列
dp = [[0] * (n+1) for i in range(m+1)]
for i in range(1, m+1):
for j in range(1, n+1):
if A[i-1] == B[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
# return dp[m][n]
return dp
def print_LCS(self, A, B):
dp = self.longestCommonSubsequence(A, B)
i, j = len(A), len(B)
LCS = ""
while i > 0 and j > 0:
if A[i-1] == B[j-1] and dp[i][j] == dp[i-1][j-1] + 1:
LCS = A[i-1] + LCS
i -= 1
j -= 1
continue
if dp[i][j] == dp[i-1][j]:
i -= 1
continue
if dp[i][j] == dp[i][j-1]:
j -= 1
continue
return LCS
s = Solution()
print(s.longestCommonSubsequence([1,2],[1,4,2,3]))
print(s.print_LCS('ABCD','EACB'))