1143. Longest Common Subsequence
Given two strings
text1
and text2
, return the length of their longest common subsequence. If there is no common subsequence, return 0
.Note: Having dp with index 1 makes the m-1, n-1 cases
really easy to handle for the 0-th index.
def longestCommonSubsequence(self, text1: str, text2: str):
M, N = len(text1), len(text2)
dp = [[0]*(N+1) for _ in range(M+1)]
for m in range(1, M+1):
for n in range(1, N+1):
if text1[m-1] == text2[n-1]:
dp[m][n] = dp[m-1][n-1] + 1
else:
dp[m][n] = max(dp[m-1][n], dp[m][n-1])
return dp[M][N]
Comments
Post a Comment