poj之最长公共子序列和最长公共子串

题目:poj 1458   Common Subsequence

Description

A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = < x1, x2, ..., xm > another sequence Z = < z1, z2, ..., zk > is a subsequence of X if there exists a strictly increasing sequence < i1, i2, ..., ik > of indices of X such that for all j = 1,2,...,k, x ij = zj. For example, Z = < a, b, f, c > is a subsequence of X = < a, b, c, f, b, c > with index sequence < 1, 2, 4, 6 >. Given two sequences X and Y the problem is to find the length of the maximum-length common subsequence of X and Y.

思路:题目的意思是给定两个字符串,求他们的最长公共子序列,其中子序列是可以不连续的。该题目是典型的动态规划问题,令dp[i][j]表示s1的前i个字符与s2的前j个字符的最长公共子序列,则当s1[i]==s2[j]时,dp[i+1][j+1]=dp[i][j]+1,如果不等,则dp[i+1][j+1]=max{dp[i][j+1],dp[i+1][j]},具体代码如下:

#include<iostream>
#include<vector>
#include<string>
using namespace std;

int LCS(string s1,string s2)
{
	int length1 = s1.size(),length2 = s2.size(),i,j;
	vector<vector<int> > dp(length1+1);
	for(i = 0;i <= length1;++i)
	{
		vector<int> tmp(length2+1,0);
		dp[i] = tmp;
	}
	for(i = 0;i < length1;++i)
	{
		for(j = 0;j < length2;++j)
		{
			if(s1[i] == s2[j])dp[i+1][j+1] = dp[i][j]+1;
			else dp[i+1][j+1] = max(dp[i][j+1],dp[i+1][j]);
		}
	}
	return dp[length1][length2];
}

int main()
{
	string s1,s2;
	while(cin >> s1 >> s2)
	{
		cout << LCS(s1,s2) << endl;
	}
	return 0;
}

最长公共子串

思路:两者的区别是子串要求连续的,子序列不需要连续,所以在状态转移方程中的表现就是当s1[i] != s2[j]时,d[i][j] = 0。具体如下:

#include<iostream>
#include<vector>
#include<string>
using namespace std;

int LCS(string s1,string s2)
{
	int length1 = s1.size(),length2 = s2.size(),i,j,res = 0;
	vector<vector<int> > dp(2);//这里重复使用了数组空间,即所谓的用滚动数组来减少空间复杂度,上面的子序列也可以同样进行优化
	for(i = 0;i < 2;++i)
	{
		vector<int> tmp(length2+1,0);
		dp[i] = tmp;
	}
	for(i= 0;i < length1;++i)
	{
		int k = (i+1) & 1;
		for(j = 0;j < length2;++j)
		{
			if(s1[i] == s2[j])//不相等默认为0
			{
				dp[k][j+1] = dp[k^1][j]+1;
				if(dp[k][j+1] > res)res = dp[k][j+1];
			}
		}
	}
	return res;
}

int main()
{
	string s1,s2;
	while(cin >> s1 >> s2)
	{
		cout << LCS(s1,s2) << endl;
	}
	return 0;
}


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值