forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
72 lines (55 loc) · 1.63 KB
/
main.cpp
File metadata and controls
72 lines (55 loc) · 1.63 KB
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
/// Source : https://leetcode.com/problems/longest-duplicate-substring/
/// Author : liuyubobobo
/// Time : 2019-05-19
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
/// Binary Search + Rolling Hash
/// Time Complexity: O(|S| * log(|S|))
/// Space Complexity: O(|S|)
class Solution {
private:
long long MOD = 9223372036854775807ll / 26ll;
vector<long long> power;
public:
string longestDupSubstring(string S) {
power.push_back(1ll);
for(int i = 1; i < S.size(); i ++)
power.push_back(power.back() * 26 % MOD);
int l = 0, h = S.size() - 1;
string res = "";
while(l < h){
int mid = (l + h + 1) / 2;
string tres = ok(S, mid);
if(tres != "")
l = mid, res = tres;
else
h = mid - 1;
}
return res;
}
private:
string ok(const string& s, int len){
long long base = power[len - 1];
long long hash = 0;
for(int i = 0; i < len; i ++)
hash = (hash * 26ll + (s[i] - 'a')) % MOD;
unordered_set<long long> seen;
seen.insert(hash);
for(int i = len; i < s.size(); i ++){
hash = (hash - (s[i - len] - 'a') * base % MOD + MOD) % MOD;
hash = (hash * 26ll + (s[i] - 'a')) % MOD;
if(seen.count(hash)) return s.substr(i - len + 1, len);
seen.insert(hash);
}
return "";
}
};
int main() {
cout << Solution().longestDupSubstring("banana") << endl;
// ana
cout << Solution().longestDupSubstring("abcd") << endl;
// ""
return 0;
}