1. 最长公共子串

- dp[i][j]:以str1[i]和str2[j]结尾的最长公共子串的长度

class Solution {
public:
string LCS(string str1, string str2) {
string ans;
int m = str1.size();
int n = str2.size();
int max_len = 0;
int end_i = 0;
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (str1[i - 1] == str2[j - 1]) {
if (i == 1 || j == 1 || str1[i - 2] != str2[j - 2]) {
dp[i][j] = 1;
} else {
dp[i][j] = dp[i - 1][j - 1] + 1;
}
if(dp[i][j] > max_len){
max_len = dp[i][j];
end_i = i;
}
}
}
}
return str1.substr(end_i - max_len, max_len);
}
};
2. 最长公共子序列


class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int m = text1.size();
int n = text2.size();
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; 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[m][n];
}
};