最长公共子序列&最长公共子串
来源:互联网 发布:安静 知你是神 歌词 编辑:程序博客网 时间:2024/06/03 04:46
最长公共子序列不要求连续
代码
#include<iostream>#include<vector>using namespace std;void printTheLCS(string& str1, string& str2, vector<vector<int> > path, int first, int second){if(first==0||second==0)return ;if(path[first][second]==1){ printTheLCS(str1, str2, path, first-1, second-1);cout << str1[first-1];}else if(path[first][second]==2){printTheLCS(str1, str2, path, first, second-1);}else{printTheLCS(str1, str2, path, first-1, second);}}// 1 代表左上方, 2 代表 左方, 3 代表右方void LCS(string& str1, string &str2){int len1 = str1.length();int len2 = str2.length();vector<vector<int> > dpLongest(len1+1, vector<int>(len2+1, 0));vector<vector<int> > path(len1+1, vector<int>(len2+1, 0));for(int i = 1; i <= len1; ++i)for(int j = 1; j <= len2; ++j){if(str1[i-1]==str2[j-1]){dpLongest[i][j] = dpLongest[i-1][j-1] + 1;path[i][j] = 1;}else if(dpLongest[i][j-1]>=dpLongest[i-1][j]){dpLongest[i][j] = dpLongest[i][j-1];path[i][j] = 2;}else{dpLongest[i][j] = dpLongest[i-1][j];path[i][j] = 3;}}cout << "The length of the LCS is:" << dpLongest[len1][len2] << endl;cout << "The LCS is:";printTheLCS(str1, str2, path, len1, len2);cout << endl;}int main(){string str1, str2;str1 = "abcd";str2 = "bacd";LCS(str1, str2);return 1;}
最长公共字串要求连续
代码
#include<iostream>#include<vector>using namespace std;void LCSContinuous(string& str1, string &str2){int len1 = str1.length();int len2 = str2.length();vector<vector<int> > dpLongest(len1+1, vector<int>(len2+1, 0));int maxLen = 0;int maxIndex = 0;for(int i = 0; i < len1; ++i)for(int j = 0; j < len2; ++j){if(str1[i]==str2[j]){if(i&&j)dpLongest[i][j] = dpLongest[i-1][j-1] + 1;if(i==0||j==0)dpLongest[i][j] = 1;if(dpLongest[i][j]>maxLen){maxLen = dpLongest[i][j];maxIndex = i - maxLen + 1;}}}cout << "The length of the LCS is:" << maxLen << endl;cout << "The LCS is:";int i = maxIndex;while(maxLen){cout << str1[i++];maxLen--;}cout << endl;}int main(){string str1, str2;str1 = "abcd";str2 = "bacd";LCSContinuous(str1, str2);return 1;}
0 0
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列...
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 配置hadoop2.2.0时,遇到的一些问题
- 致貌似两年的ACM生活
- 转 Android 内存溢出---Cursor
- SJTU 3001. 二哥的幸运
- Linux内核编程和用户应用程序编程的几点不同之处
- 最长公共子序列&最长公共子串
- RTL 编码指南
- 安卓加入广告的网址
- Runloop随手记
- 一、windows下安装node.js+express
- HTML选择器
- spect model
- history相关命令记录
- 【机器学习】决策树C4.5、ID3