C++代码如下:
#include <iostream>
using namespace std;
int GetLcs(string &x,string &y);
int main(int argc, const char * argv[]) {
// insert code here...
string x="ABCBDAB";
string y="BDCABA";
cout<<GetLcs(x, y);
return 0;
}
int GetLcs(string &x,string &y)
{
int maxLength=0;
int xmatch=0;
int ymatch=0;
for (int i=0; i<x.length(); i++) {
int length=0;
ymatch =0;
xmatch=i;
for (int k=xmatch; k<x.length(); k++) {
for (int j=ymatch ;j<y.length(); j++) {
if(x[k]==y[j])
{
length++;
ymatch=j+1;
break;
}
}
}
if(length>maxLength)
{
maxLength=length;
}
}
return maxLength;
}
算法时间复杂度O(nm^2)。
如有错误,感谢指出。