-
Notifications
You must be signed in to change notification settings - Fork 0
/
1044.longest-duplicate-substring.MLE.cpp
89 lines (80 loc) · 1.77 KB
/
1044.longest-duplicate-substring.MLE.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
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
* @lc app=leetcode id=1044 lang=cpp
*
* [1044] Longest Duplicate Substring
*/
// @lc code=start
auto speedup = [](){
cin.tie(nullptr);
cout.tie(nullptr);
ios::sync_with_stdio(false);
return 0;
}();
class rabinFingerprint {
public:
size_t operator()(const string& s)
{
if (m_clear) {
m_pow = 1;
for (size_t i = 1; i != s.size(); ++i) {
m_pow = (m_pow * base) % p;
}
m_cur = 0;
for (auto c : s) {
m_cur = ((m_cur * base) % p + (c - 'a')) % p;
}
m_clear = false;
} else {
m_cur = ((ssize_t(m_cur) - ssize_t(m_pow * (m_first - 'a'))) % ssize_t(p) + p) % p;
m_cur = (m_cur * base + (s.back() - 'a')) % p;
}
m_first = s.front();
return m_cur;
};
void clear() { m_clear = true; }
private:
static constexpr size_t p = 19260817;
static constexpr size_t base = 26;
bool m_clear = true;
size_t m_cur;
size_t m_pow;
char m_first;
};
struct wrapper {
size_t operator()(const string& s) const {
return m_hasher(s);
}
rabinFingerprint& m_hasher;
};
class Solution {
public:
string longestDupSubstring(string s) {
int len = s.length();
rabinFingerprint hasher;
unordered_set<string, wrapper> st{10, wrapper{hasher}};
string answer;
int low = 1;
int high = len;
while(low < high) {
int mid = (low + high) >> 1;
bool found = false;
for(int i = 0; i + mid <= len; ++ i) {
const auto [it, inserted] = st.emplace(s.data() + i, mid);
if(!inserted) {
answer = *it;
found = true;
break;
}
}
if(found) {
low = mid + 1;
} else {
high = mid - 1;
}
st.clear();
hasher.clear();
}
return move(answer);
}
};
// @lc code=end