class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int rows = text1.size();
int cols = text2.size();
int dp[rows][cols];
memset(dp, 0, sizeof(dp));
if (text1[0] == text2[0]) dp[0][0] = 1;
for (int i = 1; i < rows; i++) {
dp[i][0] = dp[i - 1][0];
if (text1[i] == text2[0]) {
dp[i][0] = 1;
}
}
for (int j = 1; j < cols; j++) {
dp[0][j] = dp[0][j - 1];
if (text1[0] == text2[j]) {
dp[0][j] = 1;
}
}
for (int i = 1; i < rows; i++)
for (int j = 1; j < cols; j++) {
if (text1[i] == text2[j]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
return dp[rows - 1][cols - 1];
}
};
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
const int cols = text2.size();
vector<int> dp(cols, 0);
for (const auto ti : text1) {
int last = dp[0];
if (ti == text2[0]) {
dp[0] = 1;
}
for (int j = 1; j < cols; j++) {
if (ti == text2[j]) {
swap(dp[j], last);
dp[j]++;
} else {
last = dp[j];
if (dp[j - 1] > dp[j])
dp[j] = dp[j - 1];
}
}
}
return dp[cols - 1];
}
};