1143. Longest Common Subsequence
# Medium
Very similar to #72, two-sequence DP problem
Subsequence: 子序列,可以跳着来
Substring: 子串,必须元素连续着
Solution:
Initialize
maxCommon[i][j]
, which means longest common substring betweentext1[:i]
andtext2[:j]
. Empty element is necessarily neededThree cases:
maxCommon[i-1][j]
. eg,abc+d
andace
maxCommon[i][j-1]
. eg,abc
andac+d
If
text1[i] = text2[j]
, thenmaxCommon[i][j] + 1
common char. eg,abc+d
andace+d
Compare to assign biggest number to
maxCommon[i][j]

class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
# initilize maxCommon
maxCommon = [[-1]*(len(text2)+1) for i in range(len(text1)+1)]
for i in range(len(text1)+1):
maxCommon[i][0] = 0
for j in range(len(text2)+1):
maxCommon[0][j] = 0
# compute
for i in range(1, len(text1)+1):
for j in range(1, len(text2)+1):
maxCommon[i][j] = max(maxCommon[i-1][j], maxCommon[i][j-1])
if text1[i-1] == text2[j-1]:
maxCommon[i][j] = max(maxCommon[i][j], maxCommon[i-1][j-1]+1)
return maxCommon[len(text1)][len(text2)]
Last updated
Was this helpful?