题目链接:点我
首先了解一下什么叫子序列:一个字符串的子序列,是指从该字符串中去掉任意多个字符后剩下的字符在不改变顺序的情况下组成的新字符串
子序列和子串还是不一样的,子串是要连续不断的,而子序列不一定是要连续的。
图示是这样的:
附上代码吧
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAX_N = 1005;
int DP[MAX_N][MAX_N];
int main()
{
char str1[MAX_N];
char str2[MAX_N];
while(cin >> str1 >> str2)
{
memset(DP, 0, sizeof(DP));
int m = strlen(str1);
int n = strlen(str2);
for(int i = 1; i <= m; i++) // 注意从1开始
{
for(int j = 1; j <= n; j++)
{
if(str1[i - 1] == str2[j - 1]) // 注意下标是i-1和j-1
DP[i][j] = DP[i - 1][j - 1] + 1;
else
DP[i][j] = max(DP[i][j - 1],DP[i -1][j]);
}
}
cout << DP[m][n] << endl;
}
return 0;
}