Advertisement
Guest User

Untitled

a guest
Dec 13th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1.     bool EqualSubArrExists(vector<int>& A, vector<int>& B, int length) {
  2.         unordered_set<long long> first_str_hashes;
  3.         const int kP = 31;
  4.         long long kP_n = 1;
  5.         for (int i = 0; i < length; ++i)
  6.             kP_n *= kP;
  7.  
  8.         // precompute all hashes of subarrays of length |length| for |A| using rolling hash algo:
  9.         long long h1 = 0;
  10.         for (int i = 0; i < length; ++i)
  11.             h1 = h1 * kP + A[i];
  12.  
  13.         first_str_hashes.insert(h1);
  14.  
  15.         for (int i = length; i < A.size(); ++i) {
  16.             h1 = (h1 - A[i - length] * kP_n) * kP + A[i];
  17.             first_str_hashes.insert(h1);
  18.         }
  19.  
  20.         // traverse all hashes in |B| and see if there is a matching hash in |first_str_hashes|:
  21.         long long h2 = 0;
  22.         for (int i = 0; i < length; ++i)
  23.             h2 = h2 * kP + B[i];
  24.         if (first_str_hashes.count(h2) > 0) return true;
  25.  
  26.         for (int i = length; i < B.size(); ++i) {
  27.             h2 = (h2 - B[i - length] * kP_n) * kP + B[i];
  28.             if (first_str_hashes.count(h2) > 0) return true;
  29.         }
  30.  
  31.         return false;
  32.     }
  33.    
  34.    
  35.     int findLengthDP(vector<int>& A, vector<int>& B) {
  36.         vector<int> dp(A.size());
  37.         int max_len = 0;
  38.        
  39.         for (auto c : B) {
  40.             for (int i = dp.size() - 1; i >= 0; --i) {
  41.                 if (A[i] == c) dp[i] = dp[i - 1] + 1;
  42.                 else  dp[i] = 0;
  43.                
  44.                 max_len = max(max_len, dp[i]);
  45.             }
  46.         }
  47.        
  48.         return max_len;
  49.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement