日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【LCS系列】最长公共子序列和最长公共子串

發布時間:2023/12/10 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【LCS系列】最长公共子序列和最长公共子串 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

最長公共子序列:

如果要回溯出整個字符串的答案的話,可以直接看dp[i][len2-1]列,或者dp[len1-1][i]這一行,變化的時候,則代表要選這個字符,然后連起來就可以了。(即構造字符串的過程是On的)?

class Solution { public:/*** longest common substring* @param str1 string字符串 the string* @param str2 string字符串 the string* @return string字符串*/int dp[5005][5005];string LCS(string str1, string str2) {// write code hereint len1 = str1.size();int len2 = str2.size();for(int i = 0; i<len1; i++) dp[i][0] = (str1[i] == str2[0])?1:dp[i-1][0];for(int i = 0; i<len2; i++) dp[0][i] = (str1[0] == str2[i])?1:dp[0][i-1];for(int i = 1; i<len1; i++) {for(int j = 1; j<len2; j++) {if(str1[i] == str2[j]) dp[i][j] = dp[i-1][j-1] + 1;else dp[i][j] = max(dp[i-1][j-1], max(dp[i-1][j], dp[i][j-1]));}}for(int i = 0; i<len1; i++) {for(int j = 0; j<len2; j++) {cout << dp[i][j] << " ";}cout << endl;}cout << dp[len1-1][len2-1] <<endl;return str1;} };

最長公共子串:

class Solution { public:/*** longest common substring* @param str1 string字符串 the string* @param str2 string字符串 the string* @return string字符串*/int dp[5005][5005];string LCS(string str1, string str2) {// write code hereint len1 = str1.size();int len2 = str2.size();for(int i = 0; i<len1; i++) dp[i][0] = (str1[i] == str2[0])?1:0;for(int i = 0; i<len2; i++) dp[0][i] = (str1[0] == str2[i])?1:0;for(int i = 1; i<len1; i++) {for(int j = 1; j<len2; j++) {if(str1[i] == str2[j]) dp[i][j] = dp[i-1][j-1] + 1;else dp[i][j] = 0;}}int mx = 0;string ans;for(int i = 0; i<len1; i++) {for(int j = 0; j<len2; j++) {if(dp[i][j] > mx) {mx = dp[i][j];ans = str1.substr(i-mx+1, mx);}}}return ans;} };

總結

以上是生活随笔為你收集整理的【LCS系列】最长公共子序列和最长公共子串的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。