您的位置:首页 > 编程语言 > C语言/C++

C++实现最长公共子序列LCS问题

2018-01-24 10:16 435 查看
LCLCS问题求解:







#include<iostream>
#include<stdio.h>
#include<string.h>
#include<vector>
#include<algorithm>

using namespace std;

void LCS(const char *str1, const char *str2, string &str){
int size_1 = (int)strlen(str1);
int size_2 = (int)strlen(str2);
// 从1开始计数,方便后面写代码
const char*s1 = str1 - 1;
const char*s2 = str2 - 1;
vector<vector<int> > chess(size_1 + 1, vector<int>(size_2 + 1));
int i, j;
for(i = 0; i <= size_1; i++)
chess[i][0] = 0;
for(j = 0; j <= size_2; j++)
chess[0][j] = 0;

for(i = 1; i <= size_1; i++){
for(j = 1; j <= size_2; j++){
if(s1[i] == s2[j])
chess[i][j] = chess[i-1][j-1] + 1;
else
chess[i][j] = max(chess[i][j-1], chess[i-1][j]);
}
}

for(i = 0; i <= size_1; i++){
for(j = 0; j <= size_2; j++)
cout<<chess[i][j]<<" ";
cout << endl;
}

i = size_1;
j = size_2;
while((i != 0) && (j != 0)){
if(s1[i] == s2[j]){
str.push_back(s1[i]);
i--;
j--;
}else{
if(chess[i][j-1] > chess[i-1][j])
j--;
else
i--;
}
}
reverse(str.begin(), str.end());
}

int max(int x, int y){
return (x>y)?x:y;
}

int main(int argc, char *argv[]){
const char *str1 = argv[1];
const char *str2 = argv[2];
string str;
LCS(str1, str2, str);
cout<< str.c_str() << endl;

return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: