//============================================================================
// Name : reversestring.cpp
// Author : qxyu
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include<vector>
#include<algorithm>
#include<cmath>
#include<queue>
#include<map>
#include<stack>
#include<string>
#include<unordered_map>
#include<memory>
//#include<uint32_t>
using namespace std;
/**
* Definition for a point.
*/
int flag[51][51];
void lcs(string& a, string& b ){
int num[51][51]={0};
for(int i = 0; i < a.size(); i ++){
for(int j=0; j < b.size(); j ++){
if(a[i]==b[j]){
num[i][j]=num[i-1][j-1]+1;
flag[i][j]=1;
}
else if(num[i][j-1]>num[i-1][j])
{
num[i][j]=num[i][j-1];
flag[i][j]=2;
}
else {
num[i][j]=num[i-1][j];
flag[i][j]=3;
}
}
}
}
string getLcs(string& a, string& b){
string res;
int i = a.size()-1;
int j = b.size()-1;
while( i >=0 &&j >=0){
if(flag[i][j]==1)
{
res.push_back(a[i]);
i--;
j--;
}
else if(flag[i][j]==2)
j--;
else
i--;
}
return res;
}
int main()
{
string a = "ABCBDAB";
string b = "BDCABA";
lcs(a,b);
string c=getLcs(a,b);
for(int i = c.size()-1; i >=0; i--)
cout<<c[i];
return 0;
}
最长公共子序列
最新推荐文章于 2024-07-20 22:14:11 发布