题目(最长公共子序列)
给你输入两个字符串 s1 和 s2,请你找出他们俩的最长公共子序列,返回这个子序列的长度。比如:
输入: str1 = "abcde", str2 = "ace"
输出: 3
解释: 最长公共子序列是 "ace",它的长度是 3
AC代码
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int main()
{
// char a[1002],b[1002];
string a, b;
int i, j, len_a, len_b;
int temp[499][499];
while (cin >> a >> b)
{
len_a = a.length();
len_b = b.length();
memset(temp, 0, sizeof(temp)); // 不加这一句就报 运行时错误
for (i = 1; i <= len_a; i++)
{
for (j = 1; j <= len_b; j++)
{
if (a[i - 1] == b[j - 1])
temp[i][j] = temp[i - 1][j - 1] + 1;
else
temp[i][j] = max(temp[i - 1][j], temp[i][j - 1]);
}
}
cout << temp[len_a][len_b] << endl;
}
}