目录
题目
待添加
解法一
cpp
int max(int a, int b) {
return a > b ? a : b;
}
int longestCommonSubsequence(char* text1, char* text2) {
const int len1 = strlen(text1), len2 = strlen(text2);
// 将长度较小的字符串作为text2,节省dp数组的空间
if (len1 < len2) {
return longestCommonSubsequence(text2, text1);
}
int dp[len2 + 1];
memset(dp, 0, sizeof(dp));
// 当前位置与左边、上边和左上位置有关
for (int i = 1; i <= len1; i++) {
int leftUp = dp[0];
for (int j = 1; j <= len2; j++) {
int backup = dp[j];
if (text1[i - 1] == text2[j - 1]) {
dp[j] = leftUp + 1;
} else {
dp[j] = max(dp[j - 1], dp[j]);
}
leftUp = backup;
}
}
return dp[len2];
}