最长公共子序列(c++实现)

问题:给定两个长度分别为m,n的字符串,求他们的最长公共子序列,要求时间复杂度为O(m+n)。

解决思路:

声明两个二维数组,cArray[i][j]代表在此位置时两个字符串已经存在了多少公共字符,sArray[i][j]用于回溯找到最长公共子序列。

代码实现:

#include"pch.h"
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;

string LCS(string firstStr, string secondStr)
{
	int x = firstStr.size() + 1;
	int y = secondStr.size() + 1;

	//申请动态生成的二维数组
	int **cArray = new int*[x];
	int **sArray = new int*[x];
	for (int i = 0; i < x; i++)
	{
		cArray[i] = new int[y];
		sArray[i] = new int[y];
	}

	//初始化动态生成的cArray
	for (int j = 0; j < y; j++)
	{
		cArray[0][j] = 0;
		sArray[0][j] = 0;
	}
	for (int i = 0; i < x; i++)
	{
		cArray[i][0] = 0;
		sArray[i][0] = 0;
	}
	
	string result = "";
	//开始处理两个字符串
	for (int i = 1; i <= firstStr.length(); i++)
	{
		for (int j = 1; j <= secondStr.length(); j++)
		{
			if (secondStr[j - 1] == firstStr[i - 1])
			{
				cArray[i][j] = cArray[i - 1][j - 1] + 1;
				sArray[i][j] = 1;
			}
			else
			{
				if (cArray[i][j - 1] <= cArray[i - 1][j])
				{
					cArray[i][j] = cArray[i - 1][j];
					sArray[i][j] = 2;
				}
				else
				{
					cArray[i][j] = cArray[i][j - 1];
					sArray[i][j] = 3;
				}
			}
		}
	}
	
	/*for (int i = 0; i < x; i++)
	{
		for (int j = 0; j < y; j++)
		{
			cout << cArray[i][j] << " ";
		}
		cout << endl;
	}*/
	int i = firstStr.size();
	int j = secondStr.size();
	while (i >= 1 && j >= 1)
	{
		if (sArray[i][j] == 1)
		{
			result += firstStr[i - 1];
			i--;
			j--;
		}
		else if (sArray[i][j] == 2)
		{
			i--;
		}
		else if (sArray[i][j] == 3)
		{
			j--;
		}
	}
	//反转字符串
	int m = result.size() / 2;
	for (int j = 0; j < m; j++)
	{
		char temp = result[j];
		result[j] = result[result.size() - 1 - j];
		result[result.size() - 1 - j] = temp;
	}
	return result;
}
int main()
{
	string firstStr;
	string secondStr;
	cout << "Enter first string: ";
	cin >> firstStr;
	cout << "Enter second string: ";
	cin >> secondStr;
	string result = LCS(firstStr, secondStr);
	if (result.size() == 0)
	{
		cout << "No common string between two strings.\n";
	}
	else
	{
		cout << "The longest common string is " << result << endl;
	}
}

实现效果:

  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值