Longest Common Subsequence
ID: 1143
Given two strings text1
and text2
, return the length of their longest common subsequence. If there is no common subsequence, return 0
.
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.
For example,
"ace"
is a subsequence of"abcde"
.
A common subsequence of two strings is a subsequence that is common to both strings.
Idea
Truncate from the end of each string text, if the end of both string matches, then calculate the result for this particular index with the next index of both strings.
For example, dp[i][j] = dp[i+1][j+1]+1, since current i, j matchs, so the resulting subsequence length is the later one increment by 1
If not, get the max from dp[i+1][j] and dp[i][j+1]
Code
Last updated