Guest User

Untitled

a guest
Sep 15th, 2019
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1.  
  2. #define ll unsigned long long int
  3. #define p 31
  4. #define hell 188748146801
  5.  
  6. class Solution {
  7. public:
  8.    
  9.     ll power(ll x,ll n)
  10. {
  11.     if(n==0)
  12.         return 1;
  13.     if(n%2==0)
  14.         return power((x*x)%hell,n/2)%hell;
  15.     else
  16.         return (x*(power((x*x)%hell,n/2)%hell))%hell;
  17. }
  18.    
  19.     ll check(string &s,ll k)
  20.     {
  21.     /*mp stores the hash value and ending index of corresponding hash value\
  22.      i.e the ending index of the substring*/
  23.     unordered_map <ll,ll> mp;
  24.     ll h=0;
  25.     //for rolling hash
  26.     ll pp=power(p,k-1);
  27.     for(ll i=0;i<k;i++)
  28.         h=(h*p+s[i]-'a'+1)%hell;
  29.     mp[h]=k-1;
  30.     for(ll i=k;i<s.length();i++)
  31.     {
  32.         h=(h-pp*(s[i-k]-'a'+1)+hell)%hell;
  33.         h=(h*p+s[i]-'a'+1)%hell;
  34.         /* if the starting point of current susbtring is greater
  35.             than the ending point of previously seen hash then this string is repeating
  36.         */
  37.         if(mp.count(h))
  38.             return mp[h]-k+1;
  39.         mp[h]=i;
  40.     }
  41.     return -1;
  42. }
  43.    
  44.     string longestDupSubstring(string s) {
  45.         if(s.length()==0)
  46.             return "";
  47.         int l,h,m,ans,id;
  48.         l=0;
  49.         h=s.length();
  50.         ans=0;
  51.         while(l<=h){
  52.             m=l+(h-l)/2;
  53.             int c=check(s,m);
  54.             if(c!=-1){
  55.                 ans=m;
  56.                 id=c;
  57.                 l=m+1;
  58.             }
  59.             else
  60.                 h=m-1;
  61.         }
  62.       //  cout<<ans<<"\n";
  63.         if(ans==0)
  64.             return "";
  65.         return s.substr(id,ans);
  66.     }
  67. };
Add Comment
Please, Sign In to add comment