Problem P11. [算法课动态规划]最长公共子序列
给定两个字符串 text1 和 text2,返回这两个字符串的最长 公共子序列 的长度。如果不存在 公共子序列 ,返回 0
输入
输入字符串s1和s2
输出
输出最长公共子序列的长度
样例
标准输入复制文本 |
abcde ace |
标准输出复制文本 |
3 |
标准输入复制文本 |
asdfg azxcd |
标准输出复制文本 |
2 |
提示
区分两个概念:子序列可以是不连续的;子数组(子字符串)需要是连续的
#include<iostream>
#include<vector>
#include<string>
#include<cmath>
#include<sstream>
#include<math.h>
using namespace std;
class Solution{
public:
int longestCommonSubsequence(string text1,string text2){
int m = text1.length(), n = text2.length();
vector<vector<int>> dp(m + 1, vector<int>(n + 1));
for (int i = 1; i <= m; i++) {
char c1 = text1.at(i - 1);
for (int j = 1; j <= n; j++) {
char c2 = text2.at(j - 1);
if (c1 == c2) {
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];
}
};
int main(){
string text1;
string text2;
cin>>text1;
cin>>text2;
Solution sol;
cout<<sol.longestCommonSubsequence(text1,text2);
return 0;
}