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

来源:互联网 发布:三鼎全站仪数据编辑 编辑:程序博客网 时间:2024/05/16 17:56
<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 0
原创粉丝点击