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;
}
#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;
}
相关文章推荐
- LCS问题(最长公共子序列)-动态规划实现
- LCS最长公共子序列C++代码实现
- LCS问题(最长公共子序列)-动态规划实现
- python实现求解最长公共子序列LCS问题
- 【经典算法】:最长公共子序列(LCS问题,用遍历实现)
- LCS问题(最长公共子序列)-动态规划实现
- 最长公共子序列(LCS)的C++实现
- 算法学习 - 最长公共子序列(LCS)C++实现
- LCS问题(最长公共子序列)-动态规划实现
- 最长公共子序列LCS(C++实现)
- LCS问题(最长公共子序列)-动态规划实现
- 动态规划之最长公共子序列问题 C++实现
- 一个无聊男人的疯狂《数据结构与算法分析-C++描述》学习笔记 用C++/lua/python/bash的四重实现(3) 最大子序列和问题
- 仿MFC实现c++按名动态创建对象之续(瘦身以及解决其在dll中使用的问题)
- 贪心算法运用于背包问题(C++实现)
- 最长公共子序列(LCS)问题
- 一笔画问题的c++实现
- socket简单实现ftp的文件传送(C++V2.0版,解决数据丢失问题)
- VC++编译问题汇总1 单链表的表示和实现,基于c++
- Singleton的C++实现 及相关问题