-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathLC1044.cpp
executable file
·75 lines (66 loc) · 1.52 KB
/
LC1044.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
Problem Statement: https://leetcode.com/problems/longest-duplicate-substring/
Time: O(n² • log n), amortized O(n • log n)
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class RabinKarp {
private:
int hash, mod;
long long d, p;
public:
RabinKarp(const string& pat) : hash(0), mod(1e9 + 7), d(26), p(1) {
int m = pat.length();
for (char c: pat)
hash = (d * hash + (c - 'a')) % mod;
for (int i = 0; i < m - 1; i++)
p = (d * p) % mod;
}
void push(char& c1, char& c2) {
hash = (hash - p * (c1 - 'a')) % mod;
if (hash < 0)
hash += mod;
hash = (d * hash + (c2 - 'a')) % mod;
}
int get_hash() {
return hash;
}
};
class Solution {
public:
string longestDupSubstring(string S) {
string dup;
int n, low, mid, high;
low = 0;
high = n = S.length();
// helper function
auto good = [&](int x) {
RabinKarp rk(S.substr(0, x));
unordered_map<int, vector<int>> m;
m[rk.get_hash()].push_back(0);
for (int i = x; i < n; i++) {
rk.push(S[i - x], S[i]);
auto it = m.find(rk.get_hash());
if (it != m.end()) { // found hash in map
string s = S.substr(i - x + 1, x);
for (int j: it->second)
if (s == S.substr(j, x)) { // make sure it is not a collision
dup = S.substr(i - x + 1, x);
return true;
}
}
m[rk.get_hash()].push_back(i - x + 1);
}
return false;
};
// binary search
while (low < high) {
mid = (low + high) / 2;
if (good(mid))
low = mid + 1;
else
high = mid;
}
return dup;
}
};