前面已经参考了几个blog和看了资料,今天自己实现下。
题目以及思想:http://hzzy-010.blog.163.com/blog/static/79692381200872024242126/
#include <iostream>
#include <string>
#include <cstring>
#define maxn 100
using namespace std;
class LCS{
public:
string ans(const string lft, const string rht);
private:
string output(const int &m , const int &n, const string &lft, const string &rht);
int map[maxn][maxn];
int dir[maxn][maxn]; //0 as not set, 1 pos lft, 2 point to up , 3 other
};
string LCS::ans(string lft, string rht){
memset(map, 0, sizeof(map));
memset(dir, 0, sizeof(dir));
for(int i = 1; i <= lft.size(); i++)
for(int j = 1; j <= rht.size(); j++){
if(lft[i - 1] == rht[j - 1]){
map[i][j] = map[i - 1][j - 1] + 1;
dir[i][j] = 3;
}else if(map[i - 1][j] > map[i][j -1]){
map[i][j] = map[i - 1][j];
dir[i][j] = 1;
}else{
map[i][j] = map[i][j - 1];
dir[i][j] = 2;
}
}
return output(lft.size(), rht.size(), lft, rht);
}
string LCS::output(const int &m, const int &n, const string &lft, const string &rht){
//cout << m << n << lft << " " << rht;
int x, y;
x = m, y = n;
if(x == 0 || y == 0 || !dir[m][n]){
string ret;
return ret;
}else{
string tmp;
switch(dir[x][y]){
case 1:
x--;
break;
case 2:
y--;
break;
case 3: x--;
y--;
break;
}
if(lft[m - 1] == rht[n - 1]){
return output(x, y, lft, rht) + lft[m - 1];
}else{
return output(x, y, lft, rht);
}
}
}
int main()
{
string str1 = "ACCGGTCGAGTGCGCGGAAGCCGGCCGAA";
string str2 = "GTCGTTCGGAATGCCGTTGCTCTGTAAA";
LCS test;
cout << test.ans(str1, str2) << endl;
return 0;
}