forked from shruti170901/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Longest Duplicate Substring.cpp
46 lines (45 loc) · 1.34 KB
/
Longest Duplicate Substring.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
class Solution {
public:
static constexpr long long MOD = 1000000007;
bool check(string& s, int len) {
unordered_map<long long, vector<int>> lookup;
long long sum = 0, mult = 1;
for (int i = 0; i < n; ++i) {
int num = s[i] - 'a';
sum = (sum * 26 + num) % MOD;
if (i >= len) {
sum = (sum - mult * (s[i-len] - 'a')) % MOD;
while (sum < 0)
sum += MOD;
sum %= MOD;
} else
mult = (mult * 26) % MOD;
auto& vect = lookup[sum];
int index = i-len+1;
for (int j: vect) {
if (s.compare(index, len, s, j, len) == 0) {
pos = j, length = len;
return true;
}
}
if (i >= len - 1)
vect.push_back(index);
}
return false;
}
int n, pos, length;
string longestDupSubstring(string& s) {
vector<vector<int>> indexes(26);
n = s.size();
length = -1;
int lo = 1, hi = n-1;
while (lo <= hi) {
int mid = (lo+hi) / 2;
if (check(s, mid))
lo = mid + 1;
else
hi = mid - 1;
}
return (length >= 0) ? s.substr(pos, length) : "";
}
};