Advertisement
asdfg0998

Untitled

Apr 1st, 2025
626
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. int longestSubsequenceEfficient(std::string x, std::string y) {
  2.     int m = x.length();
  3.     int n = y.length();
  4.     int result = 0;
  5.    
  6.     // For each starting position in y
  7.     for (int i = 0; i < n; i++) {
  8.         // Early termination if remaining length can't beat current max
  9.         if (n - i <= result) break;
  10.        
  11.         // Use a sliding window approach with two pointers
  12.         std::vector<std::vector<int>> next(n + 1, std::vector<int>(26, -1));
  13.        
  14.         // Precompute next occurrence of each character
  15.         for (int j = n - 1; j >= i; j--) {
  16.             for (int c = 0; c < 26; c++) {
  17.                 next[j][c] = next[j + 1][c];
  18.             }
  19.             next[j][y[j] - 'a'] = j;
  20.         }
  21.        
  22.         // Try to match each substring starting at position i
  23.         for (int len = 1; i + len - 1 < n; len++) {
  24.             bool isSubsequence = true;
  25.             int pos = 0;
  26.            
  27.             // Check if y[i...i+len-1] is a subsequence of x
  28.             for (int j = i; j < i + len; j++) {
  29.                 // Find the next occurrence of y[j] in x starting from pos
  30.                 while (pos < m && x[pos] != y[j]) {
  31.                     pos++;
  32.                 }
  33.                
  34.                 if (pos >= m) {
  35.                     isSubsequence = false;
  36.                     break;
  37.                 }
  38.                 pos++; // Move to the next position in x
  39.             }
  40.            
  41.             if (isSubsequence) {
  42.                 result = std::max(result, len);
  43.             } else {
  44.                 // If current length is not a subsequence, longer ones won't be either
  45.                 break;
  46.             }
  47.         }
  48.     }
  49.    
  50.     return result;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement