class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
if (text1.empty() || text2.empty()) {
return 0;
}
if (text1.size() < text2.size()) {
swap(text1, text2);
}
vector<vector<int>>dp(text1.size() + 1, vector<int>(text1.size() + 1, 0));
for (int i = 1; i <= text1.size(); i++) {
for (int j = 1; j <= text2.size(); j++) {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
if (text1[i - 1] == text2[j - 1]) {
dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 1);
}
}
}
return dp[text1.size()][text2.size()];
}
};
string longestCommonSubString(string &str1, string &str2) {
if(str1.empty() || str2.empty()) return "";
vector<vector<int>> dp(str1.size()+1, vector<int>(str2.size()+1, 0));
int maxLen = 0;
int end = 0;
for (int i = 1; i <= str1.size(); ++i) {
for (int j = 1; j <= str2.size(); ++j) {
dp[i][j] = str1[i-1] == str2[j-1] ? dp[i-1][j-1]+1 : 0;
if (dp[i][j] > maxLen){
maxLen = dp[i][j];
end = i-1;
}
}
}
return str1.substr(end - maxLen + 1, maxLen);
}