最长公共子序列&最长公共子串

最长公共子序列不要求连续

代码

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

void printTheLCS(string& str1, string& str2, vector<vector<int> > path, int first, int second)
{
	if(first==0||second==0)
		return ;
	if(path[first][second]==1)
	{ 
		printTheLCS(str1, str2, path, first-1, second-1);

		cout << str1[first-1];
	
	}
	else if(path[first][second]==2)
	{
		printTheLCS(str1, str2, path, first, second-1);
	
	}
	else
	{
		printTheLCS(str1, str2, path, first-1, second);
	}
}





// 1  代表左上方, 2 代表 左方, 3 代表右方
void LCS(string& str1, string &str2)
{
	int len1 = str1.length();
	int len2 = str2.length();


	vector<vector<int> > dpLongest(len1+1, vector<int>(len2+1, 0));
	vector<vector<int> > path(len1+1, vector<int>(len2+1, 0));


	for(int i = 1; i <= len1; ++i)
		for(int j = 1; j <= len2; ++j)
		{
			if(str1[i-1]==str2[j-1])
			{
				dpLongest[i][j] = dpLongest[i-1][j-1] + 1;
				path[i][j] = 1;		
			
			}
			else if(dpLongest[i][j-1]>=dpLongest[i-1][j])
			{
				dpLongest[i][j] = dpLongest[i][j-1];
				path[i][j] = 2;		
			
			}
			else
			{
				dpLongest[i][j] = dpLongest[i-1][j];
				path[i][j] = 3;

			}		
		}

		cout << "The length of the LCS is:" << dpLongest[len1][len2] << endl;

		cout << "The LCS is:";
		printTheLCS(str1, str2, path, len1, len2);
		cout << endl;

}



int main()
{
	string str1, str2;
	str1 = "abcd";
	str2 = "bacd";


	LCS(str1, str2);

	return 1;




}



最长公共字串要求连续

代码

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

void LCSContinuous(string& str1, string &str2)
{
	
	int len1 = str1.length();
	int len2 = str2.length();


	vector<vector<int> > dpLongest(len1+1, vector<int>(len2+1, 0));

	int maxLen = 0;
	int maxIndex = 0;



	for(int i = 0; i < len1; ++i)
		for(int j = 0; j < len2; ++j)
		{
			if(str1[i]==str2[j])
			{

				if(i&&j)
					dpLongest[i][j] = dpLongest[i-1][j-1] + 1;
				if(i==0||j==0)
					dpLongest[i][j] = 1;

				if(dpLongest[i][j]>maxLen)
				{
					maxLen = dpLongest[i][j];
					maxIndex = i - maxLen  + 1;
				
				}
				
			}
			

		}

		cout << "The length of the LCS is:" << maxLen << endl;

		cout << "The LCS is:";
		int i = maxIndex;
		while(maxLen)
		{
			cout << str1[i++];
			maxLen--;
		
		}
		cout << endl;



}

int main()
{
	string str1, str2;
	str1 = "abcd";
	str2 = "bacd";


	LCSContinuous(str1, str2);

	return 1;




}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值