首页 > 技术文章 > LCS

hzwackerman 2015-10-26 11:20 原文

/*
*LCS问题
*/

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
//cout << "hello, world" << endl;
string str1 = "abcbdab";
string str2 = "bdcaba";
int x_len = str1.length();
int y_len = str2.length();
int i, j;
int arr[50][50] = {0};

cout << str1 << endl << str2 << endl;
for(i = 1; i <= x_len; i++){
for(j = 1; j <= y_len; j++){
if(str1[i-1] == str2[j-1])
{
arr[i][j] = arr[i-1][j-1] + 1;
}
else
{
if(arr[i][j-1] >= arr[i-1][j])
arr[i][j] = arr[i][j-1];
else
arr[i][j] = arr[i-1][j];
}
}
}
//
for(i = 0 ; i <= x_len; i++)
{
for(j = 0; j <= y_len; j++)
cout << arr[i][j] << " ";
cout << endl;
}

//

string ret;
for(i = x_len,j = y_len; i >= 1 && j >= 1; )
{
if(str1[i-1] == str2[j-1]){
//cout << str1[i-1] << " ";
ret += str1[i-1];
i--;
j--;
}
else{
if(arr[i][j-1] > arr[i-1][j])
{
j--;
}
else
i--;
}
}
reverse(ret.begin(), ret.end());
cout << ret;
cout << endl;
return 0;
}

推荐阅读