最长公共子序列,DP,LCS

题目描述:

Find a longest common subsequence of two strings.

输入:

First and second line of each input case contain two strings of lowercase character a…z. There are no spaces before, inside or after the strings. Lengths of strings do not exceed 100.

输出:

For each case, output k – the length of a longest common subsequence in one line.

样例输入:
abcd
cxbydz
样例输出:
2
来源:

2008年上海交通大学计算机研究生机试真题


#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
const int maxn = 1e2 + 7;
int dp[maxn][maxn];
int LCS(string strA, string strB) {
	int m = strA.length(), n = strB.length();
	strA = " " + strA;
	strB = " " + strB;
	for (int i = 0; i <= m; ++i)
		dp[i][0] = 0;
	for (int j = 0; j <= n; ++j)
		dp[0][j] = 0;
	for (int i = 1; i <= m; ++i)
		for (int j = 1; j <= n; ++j)
			dp[i][j] = max(max(dp[i - 1][j], dp[i][j - 1]),
				dp[i - 1][j - 1] + ((strA[i] == strB[j]) ? 1 : 0));
	return dp[m][n];
}

int main() {
	string strA, strB;
	while (cin >> strA >> strB) {
		cout << LCS(strA, strB) << endl;
	}
	return 0;
}
另个字符串下标从1开始,dp[i][j]表示 strA[1:i] 和 strB[1:j]的最长公共子序列长度,我们要求dp[m][n] m为串A的长度,n为串B的长度。 时间复杂度O(mn)

dp方程:

i = 0 时,dp[0][j] = 0; for any j <= n

j = 0 时, dp[i][0] = 0; for any i <= m;

0 < i <= m; 0 < j <= n时, dp[i][j] = max(dp[i -1][j], dp[i][j -1], dp[i -1][j -1] + (strA[i] == strB[j]));

max中的三部分分别为,算了我描述不好,根据dp数组的定义就可以看出来。dp[i][j]表示 strA[1:i] 和 strB[1:j]的最长公共子序列长度

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值