Longest Common Subsequence
Given two strings text1 and text2, return the length of the longest common subsequence between the two strings if one exists, otherwise return 0.
A subsequence is a sequence that can be derived from the given sequence by deleting some or no elements without changing the relative order of the remaining characters.
For example, “cat” is a subsequence of “crabt”.
A common subsequence of two strings is a subsequence that exists in both strings.
Example 1:
Input: text1 = "cat", text2 = "crabt"
Output: 3
Explanation: The longest common subsequence is “cat” which has a length of 3.
Example 2:
Input: text1 = "abcd", text2 = "abcd"
Output: 4
Example 3:
Input: text1 = "abcd", text2 = "efgh"
Output: 0
Constraints:
1 <= text1.length, text2.length <= 1000
text1 and text2 consist of only lowercase English characters.
Solution
Let d p [ i ] [ j ] dp[i][j] dp[i][j] represents the length of longest common subsequence between t e x t 1 0 : i text1_{0:i} text10:i and t e x t 2 0 : j text2_{0:j} text20:j. If t e x t 1 [ i ] = = t e x t 2 [ j ] text1[i]==text2[j] text1[i]==text2[j], then we can transfer from d p [ i − 1 ] [ j − 1 ] dp[i-1][j-1] dp[i−1][j−1] that d p [ i ] [ j ] = d p [ i − 1 ] [ j − 1 ] + 1 dp[i][j] = dp[i-1][j-1]+1 dp[i][j]=dp[i−1][j−1]+1. Or d p [ i ] [ j ] dp[i][j] dp[i][j] will be max ( d p [ i − 1 ] [ j ] , d p [ i ] [ j − 1 ] ] ) \max(dp[i-1][j], dp[i][j-1]]) max(dp[i−1][j],dp[i][j−1]]), because t e x t 1 [ i ] text1[i] text1[i] and t e x t 2 [ j ] text2[j] text2[j] do not make any contribution to the common subsequence.
Code
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
dp = [[0]*len(text2) for _ in range(len(text1))]
for j in range(len(text2)):
dp[0][j] = 1 if text1[0] == text2[j] else 0
for j in range(1, len(text2)):
dp[0][j] = max(dp[0][j], dp[0][j-1])
for i in range(1, len(text1)):
dp[i][0] = 1 if text1[i] == text2[0] else 0
dp[i][0] = max(dp[i][0], dp[i-1][0])
for j in range(1, len(text2)):
if text1[i] == text2[j]:
dp[i][j] = dp[i-1][j-1]+1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
print(dp)
return dp[-1][-1]