HackerRank - common-child【DP】
题意
给出两串长度相等的字符串,找出他们的最长公共子序列e
思路
字符串版的LCS
AC代码
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set>
#include <cstdlib>
#include <ctype.h>
#include <numeric>
#include <sstream>
using namespace std;
typedef long long LL;
const double PI = 3.14159265358979323846264338327;
const double E = 2.718281828459;
const double eps = 1e-6;
const int MAXN = 0x3f3f3f3f;
const int MINN = 0xc0c0c0c0;
const int maxn = 1e3 * 5 + 5;
const int MOD = 1e9 + 7;
int dp[maxn][maxn];
int main()
{
string a, b;
cin >> a >> b;
int i, j;
int len = a.size();
memset(dp, 0, sizeof(dp));
for (i = 0; i < len; i++)
{
if (i)
{
dp[0][i] = dp[0][i - 1];
dp[i][0] = dp[i - 1][0];
}
if (a[0] == b[i])
dp[0][i] = 1;
if (b[0] == a[i])
dp[i][0] = 1;
}
for (i = 1; i < len; i++)
{
for (j = 1; j < len; j++)
{
if (a[i] == b[j])
dp[i][j] = dp[i - 1][j - 1] + 1;
else
dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
}
}
cout << dp[len - 1][len - 1] << endl;
}