动态规划------最长公共子串(连续)
采用二维数组来求解,只返回长度
int lcs(string s1,int n,string s2, int m) { int result = 0; vector<vector<int>> c(n+1,vector<int> (m+1,0)); for (int i = 1; i < n+1; i++) for (int j = 1; j < m+1; j++) { if (s1[i - 1] == s2[j - 1]) { c[i][j] = c[i-1][j - 1] + 1; result = max(result, c[i][j]); } else c[i][j] = 0; } return result; }
采用两个一维数组,一个存储当前值,一个存储上一轮字符串比较的值,并输出公共最长字符串
int lcs(string s1,int n,string s2, int m) { int result = 0;//字符串中连续相等的字符数的最大值 int pos = 0;//result出现的在字符串中的位置 vector<int> tmp(m, 0); //保存矩阵的上一行 vector<int> c(tmp);//保存当前行 for (int i = 0; i < n; i++) { string s = s1.substr(i, 1); c.assign(m, 0); for (int j = 0; j < m; j++) { if (s2.compare(j,1,s)==0) { c[j] = (j == 0 ? 1 : (tmp[j - 1] + 1)); if (c[j]>result) { result = c[j]; pos = j; } } } tmp.assign(c.begin(), c.end()); } for (int i = pos - result + 1; i <= pos; ++i) cout << s2[i] << " " ; cout << endl; return result; }