题目描述
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
解:
题目意思是每个字符只要是相对顺序就可以,不用必须挨着,示例中字符串2中‘c...d...’就是最长公共子序列。
本题用暴力会超时。
动规:
dp[i][j]存放的是str1前i个字符和str2前j个字符中的最长公共子序列的长度。
如果str1[i]==str2[j]——dp[i][j] = dp[i-1][j-1] + 1;
否则——dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
#include <iostream>
using namespace std;
int main()
{
int dp[101][101];
string s1,s2;
while(cin>>s1>>s2)
{
int len1,len2;
len1 = s1.size();
len2 = s2.size();
for(int i=0; i<=len1; i++) //前面说过dp[i][j]的意思,比如dp[len1][len2]是s1
{
dp[i][0] = 0; //前len1-1个字符和s2前len2-1个字符,s1中第len1个字符
}
for(int j=0; j<=len2; j++) //的下标是s1[len-1]
{
dp[0][j] = 0;
}
for(int i=1; i<=len1; i++)
{
for(int j=1; j<=len2; j++)
{
if(s1[i-1] != s2[j-1])
{
dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
}
else
dp[i][j] = dp[i-1][j-1]+1;
}
}
cout<<dp[len1][len2]<<endl;
}
return 0;
}