https://blog.csdn.net/lisonglisonglisong/article/details/41548557
https://www.kancloud.cn/digest/pieces-algorithm/163624
https://zhuanlan.zhihu.com/p/68409952
最大公共子序列 #include<iostream> #include <stdio.h> #include <stack> #include <string> #include <vector> using namespace std; int lcs_lengh(string& str1, string& str2, vector<vector<int> >& dp) { if (str1 == "" || str2 == "") { return 0; } for (int i = 0; i <= str1.length(); i++) { dp[i][0] = 0; } for (int j = 0; j <= str2.length(); j++) { dp[0][j] = 0; } for (int i = 1; i <= str1.length(); i++) for (int j = 1; j <= str2.length(); j++) { if (str1[i-1] == str2[j-1]) { dp[i][j] = dp[i-1][j-1] + 1; } else { dp[i][j] = max(dp[i-1][j], dp[i][j-1]); } } return dp[str1.length()][str2.length()]; } void print_all_lcs_str(string& str1, string&str2, vector<vector<int> >& dp, int i, int j, string lcs_str) { while(i>0 && j>0) { if (str1[i-1] == str2[j-1]) { lcs_str = str1[i-1] + lcs_str; i--; j--; } else if (dp[i-1][j] > dp[i][j-1]) { i--; } else if (dp[i][j-1] > dp[i-1][j]) { j--; } else { print_all_lcs_str(str1, str2, dp, i-1, j, lcs_str); print_all_lcs_str(str1, str2, dp, i, j-1, lcs_str); return; //cout << " " << lcs_str << endl; } } cout << " " << lcs_str << endl; } int main() { string str1 = "abcdafafsf"; string str2 = "afksacdfads"; vector<vector<int> > dp(str1.length()+1, vector<int>(str2.length()+1)); int len = lcs_lengh(str1, str2, dp); cout << len << endl; string lcs_str; print_all_lcs_str(str1, str2, dp, str1.length(), str2.length(), lcs_str); return 0; }
最长公共子串 #include<iostream> #include <stdio.h> #include <stack> #include <string> #include <vector> using namespace std; int common_str_lengh(string& str1, string& str2, vector<vector<int> >& dp) { int max_common_len = 0; if (str1 == "" || str2 == "") { return 0; } for (int i = 0; i <= str1.length(); i++) { dp[i][0] = 0; } for (int j = 0; j <= str2.length(); j++) { dp[0][j] = 0; } for (int i = 1; i <= str1.length(); i++) for (int j = 1; j <= str2.length(); j++) { if (str1[i-1] == str2[j-1]) { dp[i][j] = dp[i-1][j-1] + 1; if (dp[i][j] > max_common_len) { max_common_len = dp[i][j]; } } else { dp[i][j] = 0; } } return max_common_len; } void print_all_common_str(vector<vector<int> >& dp, int m, int n, int max_common_len, string& str1) { string str_temp; for(int i = 1; i <= m; i++) for(int j = 1; j <= m; j++) { if (dp[i][j] == max_common_len) { int ik = i, jk = j; while(dp[ik][jk] >= 1) { str_temp.push_back(str1[ik-1]); // 注意是ik-1 ik--; jk--; } string str(str_temp.rbegin(), str_temp.rend()); if (str.length() == max_common_len) { cout << str << endl; } } } } int main() { string str1 = "abcdafafsf"; string str2 = "afksacdfads"; vector<vector<int> > dp(str1.length()+1, vector<int>(str2.length()+1)); int len = common_str_lengh(str1, str2, dp); cout << len << endl; string lcs_str; print_all_common_str(dp, str1.length(), str2.length(), len, str1); return 0; }