Coincidence
题目描述:
Find a longest common subsequence of two strings.
输入:
First and second line of each input case contain two strings of lowercase character a…z. There are no spaces before, inside or after the strings. Lengths of strings do not exceed 100.
输出:
For each case, output k – the length of a longest common subsequence in one line.
样例输入:
abcd
cxbydz
样例输出:
2
code
#include<iostream>
#include<string>
using namespace std;
//要比较的
string str1, str2;
//
int max(int a, int b)
{
return a > b ? a : b;
}
int main()
{
while (cin >> str1 >> str2)
{
//初始化
const int N = 101;
int LCS[N][N]; //存储LCS
int a = str1.length();
int b = str2.length();
//求解
for (int i = 0; i <= a; i++)
{
for (int j = 0; j <= b; j++)
{
if (i == 0)
LCS[i][j] = 0;
else if (j == 0)
LCS[i][j] = 0;
else if (str1[i-1] == str2[j-1])
LCS[i][j] = LCS[i - 1][j - 1] + 1;
else
LCS[i][j] = max(LCS[i - 1][j], LCS[i][j - 1]);
}
}
cout << LCS[a][b] << endl;
}
return 0;
}