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

C++之最长公共子序列(21)---《那些奇怪的算法》

2017-11-25 17:26 323 查看
一个char*的数组,注意其长度需要我们自己求解,另一个string类型,长度可以直接使用length方法,因此可以很棒的实现,注意,代码中的h[i][j]代表s1[0…i],s2[0…j]的最长公共子序列,我们使用动态规划方法实现!

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int lcs_(char* s1, char* s2){
int len_s1 = 0, len_s2 = 0;
while (s1[len_s1]){
len_s1++;
}
while (s2[len_s2]){
len_s2++;
}
int h[100][100] = { 0 };
for (int i = 0; i < len_s1; i++){
if (s1[i] == s2[0]) h[i][0] = 1;
}
for (int i = 0; i <len_s2; i++){
if (s1[0] == s2[i]) h[0][i] = 1;
}
for (int i = 1; i < len_s1; i++){
for (int j = 1; j < len_s2; j++){
if (s1[i] == s2[j]) h[i][j] = h[i - 1][j - 1] + 1;
else h[i][j] = h[i - 1][j] > h[i][j - 1] ? h[i - 1][j] : h[i][j - 1];
}
}
return h[len_s1 - 1][len_s2 - 1];
}
int lcs(string s1, string s2){
int h[100][100] = { 0 };
for (int i = 0; i < s1.length(); i++){
if (s1[i] == s2[0]) h[i][0] = 1;
}
for (int i = 0; i < s2.length(); i++){
if (s1[0] == s2[i]) h[0][i] = 1;
}
for (int i = 1 ; i < s1.length(); i++){
for (int j = 1 ; j < s2.length(); j++){
if (s1[i] == s2[j]) h[i][j] = h[i - 1][j - 1] + 1;
else h[i][j] = h[i - 1][j] > h[i][j - 1] ? h[i - 1][j] : h[i][j - 1];
}
}
return h[s1.length()-1][s2.length()-1];
}
int main(){
string s1 = " world";
string s2 = "hsdfa world";

int len = lcs(s1, s2);
cout << len << endl;
return 0;
}


运行结果:

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