求解两个字符串的最长公共子序列

给定两个字符串,求解这两个字符串的最长公共子序列(Longest Common Sequence)。比如字符串1:BDCABA;字符串2:ABCBDAB

则这两个字符串的最长公共子序列长度为4,最长公共子序列是:BCBA, (不要求连续)

动态规划假设给定的两个字符串为strA, strB, 令二维数组c[i,j]表示子串"strA[0], strA[1]......strA[i-1]" 与子串"strB[0], strB[1]......strB[j-1]"的最长公共子序列的长度,即 i,j代表长度, 0=< i <=strA.len, , 0=< j <=strB.len。

1)  c[i,j] = c[i-1, j-1] + 1, 若strA[i-1] == strB[j-1]

2)  c[i,j] = max{ c[i-1, j] , c[i, j-1] } , 若strA[i-1] != strB[j-1] , 即不能像情况1一样直接将最后的字符同时砍掉

3)  c[i,j] = 0 , 若i==0或 j==0

int solve(const string& strA, const string& strB) {
	const int lenA = strA.length();
	const int lenB = strB.length();

	if (lenA < 1 || lenB < 1)
		return 0;
	vector<vector<int>> cache(lenA+1, vector<int>(lenB+1,0));
	for (int subLenA = 1; subLenA <= lenA; ++subLenA) {
		for (int subLenB = 1; subLenB <= lenB; ++subLenB) {
			if (strA[subLenA - 1] == strB[subLenB - 1]) {
				cache[subLenA][subLenB] = cache[subLenA-1][subLenB-1] +1;
			}
			else {
				cache[subLenA][subLenB] = 
					std::max(cache[subLenA][subLenB - 1], cache[subLenA-1][subLenB]);
			}
		}
	}
	return cache[lenA][lenB];
}

int main() {

	int lennn = solve("BDCABA", "ABCBDAB");
        return 0;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

First Snowflakes

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值