fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. using namespace std;
  5.  
  6. int lcs(string s1, string s2) {
  7. int n = s1.size(), m = s2.size();
  8. vector<vector<int>> dp(n+1, vector<int>(m+1, 0));
  9.  
  10. for (int i = 1; i <= n; i++) {
  11. for (int j = 1; j <= m; j++) {
  12. if (s1[i-1] == s2[j-1])
  13. dp[i][j] = dp[i-1][j-1] + 1;
  14. else
  15. dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
  16. }
  17. }
  18. return dp[n][m];
  19. }
  20.  
  21. int main() {
  22. string s1 = "ABCBDAB", s2 = "BDCABA";
  23. cout << "Length of LCS: " << lcs(s1, s2) << endl;
  24. return 0;
  25. }
  26.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Length of LCS: 4