fork(3) download
  1. #include <iostream>
  2. #include <algorithm>
  3.  
  4. using namespace std;
  5.  
  6. int lcs(string x, string y)
  7. {
  8. int m = x.length();
  9. int n = y.length();
  10. int curr[n+1], prev[n+1]; // take two array of shorter length to keep track of previous rows
  11.  
  12. for (int i = 0; i <= m; i++) {
  13. for (int j = 0; j <= n; j++) {
  14. if (i == 0 || j == 0)
  15. curr[j] = 0;
  16. else {
  17. if (x[i-1] == y[j-1])
  18. curr[j]= 1 + prev[j-1];
  19. else
  20. curr[j] = max(prev[j], prev[j-1]);
  21. }
  22. }
  23.  
  24. for (int start = 0; start <= n; start++)
  25. prev[start] = curr[start];
  26. }
  27.  
  28. return curr[n];
  29. }
  30.  
  31. int wrapperLCS(string x, string y) // to keep a check that always the shorter length string is passed as second parameter
  32. {
  33. if (x.length() >= y.length())
  34. return lcs(x, y);
  35. else
  36. return lcs(y, x);
  37. }
  38.  
  39. int main()
  40. {
  41. string x = "human";
  42. string y = "chimpanzee";
  43.  
  44. cout << "Length of Longest common Subsequence : " << wrapperLCS(x, y) << endl;
  45.  
  46. return 0;
  47. }
  48.  
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
Length of Longest common Subsequence : 4