动态规划算法求两个字符串的最大公共子串

<pre name="code" class="cpp">#include "stdafx.h"
#include "windows.h"
#include <iostream>
#include <string>
#include <sstream>
#include "assert.h"

using namespace std;

//时间复杂度和空间复杂度均为 O(p*q) 其中p、q分别为两个字符串的长度,有待改进
//获取两个字符串公共子串
int GetMaxCommonSubStr(string &strFirst, string &strSecond)
{
	if((strFirst=="") || (strSecond==""))
	{
		return 0;
	}
	int i, j;
	int iLenFirst = strFirst.length();
	int iLenSecond = strSecond.length();
	int iMaxCmnLne = 0; //最大公共子串长度
	string strLCS = "";      //存储最大公共子串
	char chFirst, chSecond;
	string **num = new string *[iLenFirst];

	assert(num!=NULL);

	for(i=0; i<iLenFirst; i++)
	{
		num[i] = new string[iLenSecond];
	}

	chFirst = '\0';
	chSecond = '\0';

	for(i=0; i<iLenFirst; i++)
	{
		chFirst = strFirst.at(i);
		for(j=0; j<iLenSecond; j++)
		{
			chSecond = strSecond.at(j);
			if(chFirst != chSecond)
			{
				num[i][j] ="";
			}
			else
			{
				if(0==i || 0==j)
				{
					num[i][j] = chFirst;
				}
				else
				{
					num[i][j] = num[i-1][j-1] + chFirst;
				}

				if(num[i][j].length()>iMaxCmnLne) //如果当前获得的最大公共子串比以前的最大的大,则更新最大公共子串长度
				{
					strLCS = "";  //有新的最大公共子串,以前的作废
					iMaxCmnLne = num[i][j].length();
					strLCS = num[i][j];
				}
				else if(num[i][j].length()==iMaxCmnLne) //获取到目前为止多个当前最大公共子串,用,分得开
				{
					strLCS += ',' + num[i][j];
				}


			}

		}
	}

	//内存回收
	for(i=0; i<iLenFirst; i++)
	{
		delete [] num[i];
	}
	delete [] num;

	return iMaxCmnLne;
}


int _tmain(int argc, _TCHAR* argv[])
{

	int iResultLen;
	string strLine, InputStr1, InputStr2;
	getline(cin, strLine);

	istringstream stream(strLine);
	stream>>InputStr1;
	stream>>InputStr2;

	iResultLen = GetMaxCommonSubStr(InputStr1, InputStr2);	
	cout<<iResultLen;
	Sleep(5000);

	return 0;
}



                
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值