forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1044.Longest-Duplicate-Substring_v2.cpp
51 lines (46 loc) · 1.33 KB
/
1044.Longest-Duplicate-Substring_v2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
typedef uint64_t ULL;
class Solution {
unordered_map<int,int>len2start;
public:
string longestDupSubstring(string S)
{
int left = 1, right = S.size()-1;
while (left<right)
{
int mid = right - (right-left)/2;
if (found(S,mid))
left = mid;
else
right = mid - 1;
}
if (found(S, left))
return S.substr(len2start[left],left);
else
return "";
}
bool found(string&S, int len)
{
unordered_set<ULL>Set;
ULL base = 31;
ULL hash = 0;
ULL pow_base_len = 1;
for (int i=0; i<len-1; i++)
pow_base_len = pow_base_len * base;
for (int i=0; i<S.size(); i++)
{
if (i>=len)
hash = (hash - pow_base_len*(S[i-len]-'a') ) ;
hash = hash * base + (S[i]-'a');
if (i>=len-1)
{
if (Set.find(hash)!=Set.end())
{
len2start[len] = i-len+1;
return true;
}
Set.insert(hash);
}
}
return false;
}
};