fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. class Solution {
  6. public:
  7. int longestCommonSubsequence(string text1, string text2) {
  8. int m = text1.size();
  9. int n = text2.size();
  10. vector< vector<int>> dp(m+1, vector<int> (n+1,-1));
  11. for(int i = 0; i <= m; ++i) {
  12. for(int j = 0; j <= n; ++j) {
  13. if(i == 0 || j == 0) {
  14. dp[i][j] = 0;
  15. } else {
  16. if(text1[i-1] == text2[j-1]) {
  17. dp[i][j] = 1 + dp[i-1][j-1];
  18. } else {
  19. dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
  20. }
  21. }
  22. }
  23. }
  24. return dp[m][n];
  25. }
  26. };
  27. int main() {
  28. Solution lcs;
  29. string text1 = "abdr";
  30. string text2 = "acdr"; int ans = lcs.longestCommonSubsequence(text1,text2);
  31.  
  32. cout<<ans;
  33. }
  34.  
Success #stdin #stdout 0.01s 5516KB
stdin
Standard input is empty
stdout
3