给你输入两个字符串
s1
和s2
,请你找出他们俩的最长公共子序列,返回这个子序列的长度。比如说输入
s1 = "zabcde", s2 = "acez"
,它俩的最长公共子序列是lcs = "ace"
,长度为 3,所以算法返回 3
递归
dp
函数的定义是:dp(s1, i, s2, j)
计算s1[i..]
和s2[j..]
的最长公共子序列长度
明确选择:具体到每一个字符,思考每个字符该做什么
还有一个小的优化,情况三「s1[i]
和s2[j]
都不在 lcs 中」其实可以直接忽略
base case:i == len(s1)
或j == len(s2)
时,因为这时候s1[i..]
或s2[j..]
就相当于空串了,最长公共子序列的长度显然是 0
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
string s1, s2;
int dp(int index1,int index2) {
if (index1 == s1.length() || index2 == s2.length()) return 0;
if (s1[index1] == s2[index2])
return 1 + dp(index1 + 1, index2 + 1);
else {
return max(dp(index1 + 1, index2), dp(index1, index2 + 1));
}
}
int main() {
cin >> s1 >> s2;
cout<<dp(0, 0);
system("pause");
return 0;
}
动态规划
dp[i][j]定义:字符串A以i结尾,字符串B以j结尾的最长公共子序列长度(i,j初始为1)
base case:dp[i][0]=0(字符串B为空),dp[0][j]=0(字符串A为空)
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 101;
int dp[maxn][maxn];
int main() {
char s1[maxn], s2[maxn];
gets(s1+1); //从下标为1的位置开始存数组,这样0号位就表示空
gets(s2+1);
for (int i = 0; i <= strlen(s1+1) ; i++)
dp[i][0] = 0;
for (int j = 0; j <= strlen(s2+1); j++)
dp[0][j] = 0;
for (int i =1;i<=strlen(s1+1);i++) {
for (int j=1;j<=strlen(s2+1);j++) {
if (s1[i] == s2[j])
dp[i][j] = 1 + dp[i - 1][j - 1];
else
{
int temp_dp = max(dp[i - 1][j - 1], dp[i][j - 1]);
dp[i][j] = max(temp_dp, dp[i - 1][j]);
}
}
}
cout << dp[strlen(s1+1)][strlen(s2+1)];
system("pause");
return 0;
}