fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. int LCS(string X, string Y) {
  8. int m = X.length(), n = Y.length();
  9. vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
  10.  
  11. // Build the dp table
  12. for (int i = 1; i <= m; ++i) {
  13. for (int j = 1; j <= n; ++j) {
  14. if (X[i - 1] == Y[j - 1])
  15. dp[i][j] = 1 + dp[i - 1][j - 1];
  16. else
  17. dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
  18. }
  19. }
  20.  
  21. return dp[m][n];
  22. }
  23.  
  24. int main() {
  25. string str1 = "ABCBDAB";
  26. string str2 = "BDCAB";
  27. cout << "Length of LCS: " << LCS(str1, str2) << endl;
  28. return 0;
  29. }
  30.  
Success #stdin #stdout 0.01s 5324KB
stdin
Standard input is empty
stdout
Length of LCS: 4