最长公共子序列与子串问题

1. 最长公共子序列问题

题目:给定两个字符串str1和str2,返回两个字符串的最长公共子序列。
举例:str1="1A2C3D4B56",str2="B1D23CA45B6A"。
"123456"和"12C4B6"都是最长公共子序列,返回哪一个都行。
解法

vector<vector<int>>getdp(vector<char>str1, vector<char>str2)
{
	int m = str1.size(), n = str2.size();
	vector<vector<int>>dp(m,vector<int>(n,0));
	dp[0][0] = str1[0] == str2[0] ? 1 : 0;
	for (int i = 1; i < m; i++) {
		dp[i][0] = max(dp[i-1][0],str1[i]==str2[0]?1:0);
	}
	for (int j = 1; j < m; j++) {
		dp[0][j] = max(dp[0][j-1],str1[0]==str2[j]?1:0);
	}
	
    for (int i = 1; i < m; i++) {
		for (int j = 1; j < n; j++) {
			dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
			if (str1[i] == str2[j])
				dp[i][j] = max(dp[i][j],dp[i-1][j-1]+1);
		}
	}
	return dp;
}

void lcse(string str1, string str2)
{
	vector<char>chs1, chs2;
	for (auto c : str1)
		chs1.push_back(c);
	for (auto c : str2)
		chs2.push_back(c);
	
    vector<vector<int>>dp = getdp(chs1,chs2);
	int m = chs1.size() - 1, n = chs2.size() - 1;
	vector<char>res(dp[m][n]);
	
    int index = res.size() - 1;
	while (index >= 0) {
		if (n > 0 && dp[m][n] == dp[m][n - 1])
			n--;
		else if (m > 0 && dp[m][n] == dp[m - 1][n])
			m--;
		else {
			res[index--] = chs1[m];
			m--;
			n--;
		}
	}
	for (auto c : res)
		cout << c;
	cout << endl;
}

2. 最长公共子串问题

题目:给定两个字符串str1和str2,返回两个字符串的最长公共子串。
举例:str1="1AB2345CD",str2="12345EF",返回"2345"
解法

vector<vector<int>>getdp(vector<char>str1, vector<char>str2)
{
	int m = str1.size(), n = str2.size();
	vector<vector<int>>dp(m,vector<int>(n,0));

	for (int i = 0; i < m; i++) {
		if (str1[i] == str2[0])
			dp[i][0] = 1;
	}
	for (int j = 1; j < n; j++) {
		if (str2[j] == str1[0])
			dp[0][j] = 1;
	}
	for (int i = 1; i < m; i++) {
		for (int j = 1; j < n; j++) {
			if (str1[i] == str2[j])
				dp[i][j] = dp[i-1][j-1]+1;
		}
	}
	return dp;
}

void lcse(string str1, string str2)
{
	vector<char>chs1, chs2;
	for (auto c : str1)
		chs1.push_back(c);
	for (auto c : str2)
		chs2.push_back(c);
	vector<vector<int>>dp = getdp(chs1,chs2);
	int m = chs1.size(), n = chs2.size();
	int end = 0, max = 0;
	
	for (int i = 0; i < m; i++) {
		for (int j = 0; j < n; j++) {
			if (dp[i][j] > max) {
				end = i;
				max = dp[i][j];
			}
		}
	}
	cout << str1.substr(end-max+1,max) << endl;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值