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.
示例1
输入
abcd
cxbydz
输出
2
思路:dp[i][j]表示s1中前i个字符、s2中前j个字符组成的
两个字符串最长公共子序列长度
递推关系
dp[0][j]=0
dp[i][0]=0
dp[i][j]=dp[i-1][j-1]+1(如果s1[i-1]==s[j-1]的话)
dp[i][j]=max{dp[i-1][j], dp[i][j-1]}(如果s1[i-1]!=s[j-1]的话)
前面括号里下标要-1是因为字符串下标从0开始,s1第1个字符是s[0]
#include<iostream>
#include<cmath>
#include<cstring>
using namespace std;
int main(){
string l1,l2;
int dp[110][110];
while(cin>>l1>>l2){
for(int i=0;i<110;i++)
for(int j=0;j<110;j++)
dp[i][j]=0;
int h1=l1.size();
int h2=l2.size();
for(int i=0;i<110;i++)
dp[i][0]=0;
for(int i=0;i<110;i++)
dp[0][i]=0;
for(int i=1;i<=h1;i++){
for(int j=1;j<=h2;j++){
if(l1[i-1]==l2[j-1])
dp[i][j]=dp[i-1][j-1]+1;
else
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
cout<<dp[h1][h2]<<endl;
}
return 0;
}
该博客详细介绍了如何使用动态规划解决最长公共子序列(LCS)问题,给出了C++代码实现,并通过示例展示了算法的运行过程。内容涉及字符串处理、动态规划策略以及递推关系的建立。
1478

被折叠的 条评论
为什么被折叠?



