大概是最最基础的dp?
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.
不看提示还真想不出来
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
//这题相比起第10题模式匹配温柔多了
int l1 = text1.size();
int l2 = text2.size();
vector<vector<int>> dp(l1 + 1, vector<int>(l2 + 1));
for(int i = 1; i <= l1; i++) {
for(int j = 1; j <= l2; j++) {
if(text1[i - 1] == text2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[l1][l2];
}
};
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
l1, l2 = len(text1), len(text2)
# notice the length of array
dp = [[0] * (l2 + 1) for _ in range(l1 + 1)]
for i in range(1, l1 + 1):
for j in range(1, l2 + 1):
if text2[j - 1] == text1[i - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[l1][l2]