BKDR哈希

leetcode 1044. 最长重复子串

 1 typedef unsigned long long ull;
 2 const int N=3e4+5;
 3 const int mod=1e9+7;
 4 const int p=131;//这个取值很重要,17,19都被这题卡了;
 5 ull  px[N],hs[N];
 6 
 7 ull geths(int x,int y)
 8 {
 9     return hs[y]-hs[x-1]*px[y-x+1];
10 }
11 class Solution {
12 public:
13     string ans="";
14     string longestDupSubstring(string s) {
15        int n=s.size();
16        function<int(int)>check=[&](int len)
17        {
18            unordered_map<ull,int>mp;
19            for(int i=1;i+len-1<=n;i++)
20            {
21                int y=i+len-1;
22                ull tmp=geths(i,y);
23                if(mp[tmp])
24                {
25                    ans=s.substr(i-1,len);
26                    return 1;
27                }
28                mp[tmp]=1;
29            }
30            return 0;
31        };
32         px[0]=1;
33        for(int i=1;i<=n;i++)
34        {
35            hs[i]=hs[i-1]*p+s[i-1];
36            px[i]=px[i-1]*p;
37        }
38        int l=1,r=n;
39        while(l<=r)
40        {
41            int mid=(l+r)>>1;
42            if(!check(mid))r=mid-1;
43            else l=mid+1;
44        }   
45        return ans;
46     }
47 };

 

posted @ 2021-12-23 19:56  matt-11  阅读(113)  评论(0)    收藏  举报