LeetCode 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
.
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.
Solution
求出最长公共子序列。设 \(dp[i][j]\) 表示第一段 \([0,i)\) 和第二段 \([0,j)\) 的答案。考虑如何转移:
如果 \(text1[i-1]=text2[j-1]\):
\[dp[i][j]=1+dp[i-1][j-1]
\]
否则,取最大值:
\[dp[i][j]=\max(dp[i][j],\max(dp[i-1][j], dp[i][j-1]))
\]
点击查看代码
class Solution {
private:
int dp[1002][1002];
// dp[i][j]: [0, i), [0, j)
public:
int longestCommonSubsequence(string text1, string text2) {
int n1 = text1.length(), n2 = text2.length();
for(int i=0;i<=n1;i++){
for(int j=0;j<=n2;j++)dp[i][j]=INT_MIN;
}
for(int i=0;i<=n1;i++){
for(int j=0;j<=n2;j++){
if(i==0)dp[i][j]=0;
if(j==0)dp[i][j]=0;
}
}
for(int i=1;i<=n1;i++){
for(int j=1;j<=n2;j++){
if(text1[i-1]==text2[j-1]){
dp[i][j] = 1+dp[i-1][j-1];
}
else{
dp[i][j] = max(dp[i][j], max(dp[i-1][j], dp[i][j-1]));
}
}
}
return dp[n1][n2];
}
};