Advertisement
mickypinata

CUBE-T191: Anagram

Jul 12th, 2021
689
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef long long lli;
  5.  
  6. const int N = 2000;
  7. const int PB = 1e9 + 7;
  8.  
  9. lli anaHash[26];
  10. char strA[N + 1], strB[N + 1];
  11. int lenA, lenB;
  12.  
  13. bool sameSubstr(int len){
  14.     set<lli> st;
  15.     lli hsh = 0;
  16.     for(int i = 0; i < len; ++i){
  17.         hsh += anaHash[strA[i] - 'A'];
  18.     }
  19.     st.insert(hsh);
  20.     for(int i = len; i < lenA; ++i){
  21.         hsh -= anaHash[strA[i - len] - 'A'];
  22.         hsh += anaHash[strA[i] - 'A'];
  23.         st.insert(hsh);
  24.     }
  25.     hsh = 0;
  26.     for(int i = 0; i < len; ++i){
  27.         hsh += anaHash[strB[i] - 'A'];
  28.     }
  29.     if(st.find(hsh) != st.end()){
  30.         return true;
  31.     }
  32.     for(int i = len; i < lenB; ++i){
  33.         hsh -= anaHash[strB[i - len] - 'A'];
  34.         hsh += anaHash[strB[i] - 'A'];
  35.         if(st.find(hsh) != st.end()){
  36.             return true;
  37.         }
  38.     }
  39.     return false;
  40. }
  41.  
  42. int main(){
  43.  
  44.     anaHash[0] = 1;
  45.     for(int i = 1; i < 26; ++i){
  46.         anaHash[i] = anaHash[i - 1] * PB;
  47.     }
  48.     scanf(" %s %s", strA, strB);
  49.     lenA = strlen(strA);
  50.     lenB = strlen(strB);
  51.     int mxLen = min(lenA, lenB);
  52.     int mx = 0;
  53.     for(int i = 1; i <= mxLen; ++i){
  54.         if(sameSubstr(i)){
  55.             mx = max(mx, i);
  56.         }
  57.     }
  58.     cout << mx;
  59.  
  60.     return 0;
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement