国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

字符串應用之最長公共子序列和最長公共子串

2019-11-11 07:35:08
字體:
來源:轉載
供稿:網友

最長公共子序列

Xm表示X串的前m個字符,即x0,x1...xm?1 LCS(Xm,Yn)即X的前m個字符和Y的前n個字符的最長公共子序列。

動規方程如下: LCS(Xm,Yn)={LCS(Xm?1,Yn?1)+Xmmax(LCS(Xm?1,Yn),LCS(Xm,Yn?1)),xm=xn,xm≠yn

//最長公共子序列int longestCommonSubsequence(string A, string B) { int m = A.size(); int n = B.size(); vector<vector<int>>dp(m + 1, vector<int>(n + 1)); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (A[i] == B[j]) { dp[i + 1][j + 1] = dp[i][j] + 1; } else { dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j]); } } } int i = m - 1; int j = n - 1; string s; //記錄最長子序列并打印 while (i != -1 && j != -1) { if (A[i] == B[j]) { s += A[i]; --i; --j; } else { if ( (dp[i+1][j ] > dp[i ][j+1])) { --j; } else { --i; } } } string res(s.rbegin(), s.rend()); cout << res << endl; return dp[m][n]; // write your code here}

最長公共子串

最長公共子串,由于匹配的字串必須在A、B串都是連續的,因此在更新dp[i][j]的時候只能從dp[i-1][j-1]。

//最長公共字串int longestCommonSubstring(string &A, string &B) { // write your code here size_t m = A.size(); size_t n = B.size(); int res = 0; vector<vector<int>> dp(m, vector<int>(n)); for (int i = 0; i < static_cast<int>(m); ++i) { for (int j = 0; j < static_cast<int>(n); ++j) { if (A[i] == B[j]) { if (i>0 && j>0) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = 1; } } if (res < dp[i][j]) { res = dp[i][j]; } } } return res;}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 东方市| 从化市| 永兴县| 雷波县| 卓资县| 金湖县| 康马县| 吴忠市| 信丰县| 万山特区| 中超| 前郭尔| 商南县| 汉川市| 凤阳县| 丰台区| 措美县| 团风县| 禄劝| 平原县| 武功县| 常山县| 叙永县| 英超| 东光县| 灌南县| 阜宁县| 繁峙县| 穆棱市| 额济纳旗| 武鸣县| 万年县| 南安市| 达拉特旗| 邯郸县| 浦城县| 南雄市| 平潭县| 泰安市| 汤阴县| 安溪县|