1143. Longest Common Subsequence
Description:
Given two strings text1
and text2
, return the length of their longest common subsequence.
A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings.
If there is no common subsequence, return 0.
Solution:
1 class Solution: 2 def longestCommonSubsequence(self, text1: str, text2: str) -> int: 3 4 n1 = len(text1) 5 n2 = len(text2) 6 7 dp = [[0 for i in range(n2+1)] for j in range(n1+1)] 8 for i in range(n1): 9 for j in range(n2): 10 if text1[i]==text2[j]: 11 dp[i][j] = 1 + dp[i-1][j-1] 12 else: 13 dp[i][j] = max(dp[i-1][j], dp[i][j-1]) 14 15 return dp[n1-1][n2-1]
Notes:
2-d Dynamic Programming
O(mn)