给定两个串,均由最小字母组成。求这两个串的最大公共字串LCS(Longest Common Substring)。
使用动态规划解决。
#include <iostream> #include <vector> #include <cstring> #include <algorithm> using namespace std; #define MAX 100 int LCS(string left, string right){ int imax = -1; int m = left.size(); int n = right.size(); int i,j; int x,y; vector<vector<int> > temp(m, vector<int>(n,0)); for(i=0; i<m; i++){ for(j=0; j<n; j++){ if(left[i] == right[j]){ if (i == 0 || j == 0){ temp[i][j] = 1; }else{ temp[i][j] = temp[i-1][j-1] + 1; } if(temp[i][j] > imax){ imax = temp[i][j]; x = i; y = j; } } } } /* output the common substring */ i = x, j = y; int k = imax; string s(min(m,n),0); s[k--] = ' '; while(i>=0 && j>=0){ if(left[i] == right[j]){ s[k--] = left[i]; i--; j--; }else{ break; } } cout<<s<<endl; return imax; } int main(){ int result = 0; string query, text; cin>>query>>text; cout<<query<<endl; cout<<text<<endl; result = LCS(query, text); cout<<result; return 0; }