题目描述:
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.
样例输入:
google
goodbye
样例输出:
4
实现代码:
#include<cstdio>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 100 + 10;
int dp[maxn][maxn];
int main() {
string str1, str2;
while(cin >> str1 >> str2) {
str1 = " " + str1;
str2 = " " + str2;
for(int i = 0; i < str1.size(); i++) {
dp[i][0] = 0;
}
for(int i = 0; i < str2.size(); i++) {
dp[0][i] = 0;
}
int maxValue = 0;
for(int i = 1; i < str1.size(); i++) {
for(int j = 1; j < str2.size(); j++) {
if(str1[i] == str2[j]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
maxValue = max(maxValue, dp[i][j]);
}
}
printf("%d\n", maxValue);
}
return 0;
}