#include<iostream>
#include<string>
#include<vector>
#include <list>
using namespace std;
struct NODE
{
int nLen;
string commStr;
};
//最长公共子串,相同子串只打印一次
void LCS(string strDest,string strSur,list<NODE>&nlist)
{
int nEnd = 0;
int nLen = 0;
NODE node;
vector<vector<int> >ivec(strDest.length(),strSur.length());
for(int i = 0 ; i <strDest.length();i++)
{
for(int j =0; j <strSur.length();j++)
{
int n = (i-1) >=0&& (j-1>=0)?ivec[i-1][j-1]:0;
ivec[i][j]= strDest[i]==strSur[j]?n+1:0;
if( ivec[i][j] > nLen )
{
nLen = ivec[i][j];
nEnd = i;
node.nLen = nLen;
node.commStr = strDest.substr(nEnd - nLen+1,nLen);
nlist.push_back(node);
}
else if(ivec[i][j] == nLen && nLen != 0)
{
nLen = ivec[i][j];
nEnd = i;
node.nLen = nLen;
node.commStr = strDest.substr(nEnd - nLen+1,nLen);
for(list<NODE>::const_iterator ix = nlist.begin(); ix != nlist.end(); ix++)
{
if(ix->commStr == node.commStr)
{
nlist.erase(ix);
ix = nlist.begin();
}
}
nlist.push_back(node);
}
}
}
int nMax = 0;
for(list<NODE>::iterator ix = nlist.begin(); ix != nlist.end();ix++)
{
if(nMax <= ix->nLen)
{
nMax = ix->nLen;
}
}
if(nMax == 0)
{
cout<<"This does not match the two strings"<<endl;
return ;
}
for(list<NODE>::iterator ix = nlist.begin(); ix != nlist.end();ix++)
{
if(nMax == ix->nLen)
{
cout<<"comman str :"<<ix->commStr<<endl;
}
}
#include<string>
#include<vector>
#include <list>
using namespace std;
struct NODE
{
int nLen;
string commStr;
};
//最长公共子串,相同子串只打印一次
void LCS(string strDest,string strSur,list<NODE>&nlist)
{
int nEnd = 0;
int nLen = 0;
NODE node;
vector<vector<int> >ivec(strDest.length(),strSur.length());
for(int i = 0 ; i <strDest.length();i++)
{
for(int j =0; j <strSur.length();j++)
{
int n = (i-1) >=0&& (j-1>=0)?ivec[i-1][j-1]:0;
ivec[i][j]= strDest[i]==strSur[j]?n+1:0;
if( ivec[i][j] > nLen )
{
nLen = ivec[i][j];
nEnd = i;
node.nLen = nLen;
node.commStr = strDest.substr(nEnd - nLen+1,nLen);
nlist.push_back(node);
}
else if(ivec[i][j] == nLen && nLen != 0)
{
nLen = ivec[i][j];
nEnd = i;
node.nLen = nLen;
node.commStr = strDest.substr(nEnd - nLen+1,nLen);
for(list<NODE>::const_iterator ix = nlist.begin(); ix != nlist.end(); ix++)
{
if(ix->commStr == node.commStr)
{
nlist.erase(ix);
ix = nlist.begin();
}
}
nlist.push_back(node);
}
}
}
int nMax = 0;
for(list<NODE>::iterator ix = nlist.begin(); ix != nlist.end();ix++)
{
if(nMax <= ix->nLen)
{
nMax = ix->nLen;
}
}
if(nMax == 0)
{
cout<<"This does not match the two strings"<<endl;
return ;
}
for(list<NODE>::iterator ix = nlist.begin(); ix != nlist.end();ix++)
{
if(nMax == ix->nLen)
{
cout<<"comman str :"<<ix->commStr<<endl;
}
}
}
算法思想:
若两个字符串为:
strA: abcd
strB:cabc
strA串为行串,strB为列串
a b c d
c 0 0 1 0
a 1 0 0 0
b 0 2 0 0
c 0 0 3 0
最长长度为3,行数为3,则LCS为:3-3+1(abc)
int n = (i-1>=0)&&(j-1>=0)?ivec[i-1][j-1]:0; //0 表示当取i=0 或j=0时,默认为0
ivec[i][j]= (ivec[i] == ivec[j])?n+1:0; //若当前字符比较相等则n+1,反之则为0