动态规划算法求两个字符串的最大公共子串
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; }
相关文章推荐
- 两个或N个字符串最大公共子串算法
- 求两个字符串的最大公共子串
- 【字符串操作】 寻找两个字符串中的 最大公共子串
- java实现字符串匹配问题之求两个字符串的最大公共子串
- 两个字符串的最大公共子串
- 求两个字符串的最大公共子串
- 【python】实例-python实现两个字符串中最大的公共子串
- 求两个字符串的最大公共子串【培训第三天】
- java实现字符串匹配问题之求两个字符串的最大公共子串
- 面试题之求两个字符串的最大公共子串
- 求两个字符串最大公共子串
- 两个字符串的最大公共子串
- 求两个字符串的最大公共子串
- 求两个字符串的最大公共子串
- C++实现求两个字符串的最大公共子串
- 找出两个字符串的最大公共子串
- 求两个字符串的最大公共子串
- (Relax 后缀数组1.4)POJ 2774 Long Long Message(求两个字符串公共子串的最大长度)
- LCS求两个字符串的最大公共子串
- 两个或N个字符串最大公共子串算法