當前位置:
首頁 >
LCS(最长公共子串)系列问题
發布時間:2025/4/16
25
豆豆
生活随笔
收集整理的這篇文章主要介紹了
LCS(最长公共子串)系列问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題一
探索遞歸模式下,電腦最長計算的長度情況。(我也很神秘,為什么老師要出這種問題。。。)
就是不斷修改下面的n,來看看數值就知道了~
#include <iostream> using namespace std; #include <string>string multiply(string s, int time) {string t;for (int i = 0; i < time; ++i) t = t + s;return t; }string x, y;int lcs(int i, int j) {if (i == 0 || j == 0) return 0;if (x[i] == y[j]) return lcs(i - 1, j - 1) + 1;int temp1 = lcs(i - 1, j);int temp2 = lcs(i, j - 1);if (temp1 > temp2) return temp1;return temp2; }int main() {x = "123";y = "12";int n = 16;x = multiply(x, n);y = multiply(y, n);cout << lcs(x.length(), y.length()) << endl;system("pause"); }遞推實現,并輸出路徑
#include <iostream> using namespace std; #include <string>int lcs(string A, string B, string &C, int n, int m) {int i, j, k;int **L = new int*[n + 1];for (i = 0; i <= n; ++i) L[i] = new int[m + 1];int **S = new int*[n + 1];for (i = 0; i <= n; ++i) S[i] = new int[m + 1];for (i = 0; i <= n; ++i) L[i][0] = 0;for (j = 0; j <= m; ++j) L[0][j] = 0;for (i = 1; i <= n; ++i) {for (j = 1; j <= m; ++j) {if (A[i-1] == B[j-1]) {L[i][j] = L[i - 1][j - 1] + 1;S[i][j] = 1;}else if (L[i - 1][j] >= L[i][j - 1]) {L[i][j] = L[i - 1][j];S[i][j] = 2;}else {L[i][j] = L[i][j - 1];S[i][j] = 3;}}}k = L[n][m];C = "";for (i = 0; i < k; ++i) C.append("0");i = n, j = m;while (i != 0 && j != 0) {switch (S[i][j]){case 1:C[k-1] = A[i-1]; i--; j--; k--; break;case 2:i--; break;case 3:j--; break;}}int ans = L[n][m];for (i = 0; i <= n; ++i) delete L[i];delete[] L;for (i = 0; i <= n; ++i) delete S[i];delete[] S;return ans; }int main() {string X = "bcdbadce", Y = "cabdcbc", Z="";cout << lcs(X, Y, Z, X.length(), Y.length()) << endl;cout << Z << endl;system("pause"); }輸出:
4 bcbc思路其實很簡單,按照之前做的劃分方式就好了。
難點: 在于為什么寫為A[i-1] = = B[i-1] 還有就是后面有一個C[k-1] = A[i-1];
解釋: 因為全局的i , j都是表示的前面還有多個剩余串數量,也就是是index +1 所以這里定位回去到index的時候,就需要減一了。
問題三
遞歸式的,但是要求輸出序列。
#include <iostream> using namespace std; #include <string>typedef pair<string, int> DATA;string X = "bcdbadce", Y = "cabdcbc";DATA lcs(int i, int j) {if (i == 0 || j == 0) return {"", 0};if (X[i-1] == Y[j-1]) { DATA temp = lcs(i - 1, j - 1);temp.first.push_back(X[i-1]);temp.second++;return temp;}DATA temp1 = lcs(i - 1, j);DATA temp2 = lcs(i, j - 1);if (temp1.second >= temp2.second) return temp1;return temp2; }int main() {DATA temp = lcs(X.length(), Y.length());cout << temp.first << "\n" << temp.second << endl;system("pause"); }輸出為:
bcbc 4總結
以上是生活随笔為你收集整理的LCS(最长公共子串)系列问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【解决方案】Monkey-patchin
- 下一篇: 【修改版】10行代码爬取A股上市公司信息