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; }
运行结果:
相关文章推荐
- C++之根据组合遍历顺序生成二叉树(25)---《那些奇怪的算法》
- C++之实现大顶堆(1)---《那些奇怪的算法》
- C++之整数转化为罗马数字(11)---《那些奇怪的算法》
- C++之堆的实现(5)---《那些奇怪的算法》
- C++之求解二叉树中所有从根节点到叶节点的所有路径(23)---《那些奇怪的算法》
- C++之平衡二叉树的判定(25)---《那些奇怪的算法》
- C++之数字容器装水问题(10)---《那些奇怪的算法》
- C++实现二叉树的镜像操作(18)---《那些奇怪的算法》
- C++之求取vector中三个元素和和给定元素最接近的值(15)---《那些奇怪的算法》
- C++之罗马数字转换为整型数字(12)---《那些奇怪的算法》
- C++之树的层序遍历和深度优先遍历(先序遍历)(14)---《那些奇怪的算法》
- C++之给定向量中4个元素的和等于给定值得向量和(16)---《那些奇怪的算法》
- C++之最长回文字符串的判断(8)---《那些奇怪的算法》
- C++之字符串的zipzag排列(9)---《那些奇怪的算法》
- C++之实现两个链表合并(迭代和递归版本)(19)---《那些奇怪的算法》
- C++之归并排序(7)---《那些奇怪的算法》
- C++之最长公共子串(最长子数组和)(22)---《那些奇怪的算法》
- C++之快速排序(3)---《那些奇怪的算法》
- C++之根据组合遍历顺序生成二叉树(25)---《那些奇怪的算法》
- C++实现两个有序链表合并(17)---《那些奇怪的算法》