最长公共字串(LCS)C++代码(动态规划实现)

时间复杂度:O(n1)*O(n2),n1和n2为两个字符串的长度
注释掉#define TEST取消随机输入模式

#define TEST
#include<ctime>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
string dp(string a, string b)
{
	string res;
	int n1 = a.size(), n2 = b.size();
	int** map = new int*[n1];
	int** ch = new int* [n1];
	for (int i = 0; i < n1; ++i)map[i] = new int[n2], ch[i] = new int[n2];
	for (int i = 0; i < n1; ++i)
		for (int j = 0; j < n2; ++j)
			if (a[i] == b[j])
			{
				if (!i || !j)map[i][j] = 1;
				else map[i][j] = map[i - 1][j - 1] + 1;
				ch[i][j] = 1;
			}
			else
			{
				if (!i && !j)map[i][j] = 0, ch[i][j] = 2;
				if (!i)map[i][j] = map[i][j - 1], ch[i][j] = 3;
				else if (!j)map[i][j] = map[i - 1][j], ch[i][j] = 2;
				else if (map[i - 1][j] >= map[i][j - 1])
				{
					map[i][j] = map[i - 1][j];
					ch[i][j] = 2;
				}
				else
				{
					map[i][j] = map[i][j - 1];
					ch[i][j] = 3;
				}
			}
	int i = n1 - 1, j = n2 - 1;
	while (i >= 0 && j >= 0)
	{
		if (ch[i][j] == 1)
		{
			res = a[i] + res;
			--i, --j;
		}
		else if (ch[i][j] == 2)--i;
		else --j;
	}
	int maxi = 0;
	for (int i = 0; i < n1; ++i)
		for (int j = 0; j < n2; ++j)maxi = max(maxi, map[i][j]);
	cout <<"Length of LCS is:"<< maxi << endl;
	if (n1 <= 10 && n2 <= 10)
	{
		cout << "The direction matrix is:(1 for up and left, 2 for up and 3 for up)\n";
		for (int i = 0; i < n1; ++i) { for (int j = 0; j < n2; ++j)cout << ch[i][j] << ' '; cout << endl; }
	}
	return res;
}
int main()
{
	string a, b;
#ifdef TEST
	cout << "PLS input the lengths of the two strings: \n";
	int n1, n2;
	cin >> n1 >> n2;
	srand(time(0));
	for (int i = 0; i < n1; ++i)a += rand() % 26 + 'a';
	for (int j = 0; j < n2; ++j)b += rand() % 26 + 'a';
	cout << a << endl << b << endl;
#else
	cout << "PLS input the two strings: \n";
	cin >> a >> b;
#endif // TEST

	cout << "LCS is " << dp(a, b);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值