每日一题(86) - 计算两个字符串的最长公共子序列(LCS)

题目来自网上

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

举例:

strA = "ABCBDAB"

strB = "BDCABA"

字符串strA和strB的LCS为4.

思路:DP

代码

#include <iostream>
#include <assert.h>
#include <string>
using namespace std;

/*
f[i][j]:表示字符串strA[0~i]和字符串strB[0~j]最长公共子序列的长度

f[i][j]	= f[i - 1][j - 1] + 1;          strA[i] = strB[j]
		= max{f[i][j - 1],f[i - 1][j]}; strA[i] != strB[j]

边界条件
f[0][j] = 0;
f[i][0] = 0;
*/

int LCS(char* pStrA,char* pStrB)
{
	assert(pStrA != NULL && pStrB != NULL);
	int f[20][20];
	int nLenA = strlen(pStrA);
	int nLenB = strlen(pStrB);
	for (int i = 0;i < nLenA;i++)
	{
		f[i][0] = 0;
	}
	for (int j = 0;j < nLenB;j++)
	{
		f[0][j] = 0;
	}
	//递推
	for (int i = 1;i < nLenA;i++)
	{
		for (int j = 1;j < nLenB;j++)
		{
			if (pStrA[i] == pStrB[j])
			{
				f[i][j] = f[i - 1][j - 1] + 1;
			}
			else
			{
				f[i][j] = max(f[i - 1][j],f[i][j - 1]);
			}
		}
	}
	return f[nLenA - 1][nLenB - 1];
}


int main()  
{  
	char strA[50];  
	char strB[50];  
	string str;  
	//输入字符串A  
	cin>>str;  
	strA[0] = ' ';  
	for (int i = 0;i < str.size();i++)  
	{  
		strA[i + 1] = str[i];  
	}  
	strA[str.size() + 1] = 0;  
	//输入字符串A  
	cin>>str;  
	strB[0] = ' ';  
	for (int i = 0;i < str.size();i++)  
	{  
		strB[i + 1] = str[i];  
	}  
	strB[str.size() + 1] = 0;  

	cout<<LCS(strA,strB)<<endl; 
	system("pause");  
	return 1;  
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值