一、给定两个字符串S1和S2,求两个字符串的最长公共子序列的长度。
输入样例
ABCD
AEBD
输出样例
3
解释
S1和S2的最长公共子序列为ABD,长度为3
思路
动态规划
LCS(m,n)表示S1[0…m)和S2[0…n)的最长公共子序列的长度
S1[m-1] == S2[n-1]: LCS(m, n) = 1 + LCS(m - 1, n - 1);
S1[m-1] != S2[n-1]: LCS(m, n) = max(LCS(m - 1, n), LCS(m, n - 1))。
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class Solution{
public:
int max(int x, int y)
{
if (x <= y)
return x;
else
{
return y;
}
}
//找出最长公共子序列的长度
int lengthOflongestCommonSequence(string& str1, string& str2){
int m = str1.length(), n = str2.length();
if (m == 0 || n == 0)
return 0;
dp = vector<vector<int> >(m + 1, vector<int>(n + 1, 0));
for (int i = 1; i < m + 1; ++i){
for (int j = 1; j < n + 1; ++j){
if (str1[i - 1] == str2[j - 1])
dp[i]