您的位置:首页 > 其它

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

2014-09-03 14:29 459 查看
<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;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: