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

本文详细介绍了使用动态规划(DP)解决字符串最长公共子序列(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;  
}  


在C语言中,可以使用动态规划的方法来计算两个字符串之间的最长公共子序列(Longest Common Subsequence,简称LCS)。以下是简单的步骤: 1. 定义一个二维数组`dp`,其中`dp[i][j]`表示字符串A的前i个字符字符串B的前j个字符的最长公共子序列长度。 2. 初始化`dp`数组:如果其中一个字符串为空,那么它们的LCS就是另一个字符串的长度;如果第一个字符匹配,`dp[i][j] = dp[i-1][j-1] + 1`;如果不匹配,取当前行上一行的最大值,即`dp[i][j] = max(dp[i-1][j], dp[i][j-1])`。 3. 使用嵌套循环遍历字符串AB,填充`dp`数组。 4. 当所有元素填充完毕后,`dp[m][n]`就是两个字符串最长公共子序列长度,其中mn分别是两个字符串的长度。 5. 可以通过回溯`dp`数组找到实际的LCS。从右下角开始,对于每个`dp[i][j]`,若`dp[i-1][j] == dp[i][j]`,说明A的第i个字符不是LCS的一部分,否则它是。将非LCS部分的字符排除,逐步构建出LCS。 下面是简化的伪代码示例: ```c int lcs(char* A, char* B, int m, int n) { int dp[m+1][n+1]; // ... (填充dp数组) int index = dp[m][n]; // 最终结果 // 回溯求解LCS char lcsStr[index+1]; lcsStr[index] = '\0'; int i = m, j = n; while (i > 0 && j > 0) { if (A[i-1] == B[j-1]) { lcsStr[index-1] = A[i-1]; i--; j--; index--; } else if (dp[i-1][j] > dp[i][j-1]) { i--; } else { j--; } } return lcsStr; // 返回LCS字符串 } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值