fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // Helper function to check if 'sub' is a subsequence of 'x'
  5. bool isSubsequence(const string &x, const string &sub) {
  6. int i = 0, j = 0;
  7. while (i < x.size() && j < sub.size()) {
  8. if (x[i] == sub[j]) j++;
  9. i++;
  10. }
  11. return j == sub.size();
  12. }
  13.  
  14. int longestSubsequence(string x, string y) {
  15. int maxLen = 0;
  16. int n = y.size();
  17.  
  18. // Generate all substrings of y
  19. for (int i = 0; i < n; i++) {
  20. string temp = "";
  21. for (int j = i; j < n; j++) {
  22. temp += y[j];
  23. if (isSubsequence(x, temp)) {
  24. maxLen = max(maxLen, j - i + 1);
  25. }
  26. }
  27. }
  28.  
  29. return maxLen;
  30. }
  31.  
  32. // Example usage
  33. int main() {
  34. string x = "hackerranks";
  35. string y = "hackers";
  36. cout << longestSubsequence(x, y) << endl; // Output: 7
  37. return 0;
  38. }
  39.  
Success #stdin #stdout 0s 5304KB
stdin
Standard input is empty
stdout
7