-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path19.cpp
59 lines (45 loc) · 1.36 KB
/
19.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
/*
Longest Duplicate Substring
---------------------------
Given a string S, consider all duplicated substrings: (contiguous) substrings of S that occur 2 or more times. (The occurrences may overlap.)
Return any duplicated substring that has the longest possible length. (If S does not have a duplicated substring, the answer is "".)
Example 1:
Input: "banana"
Output: "ana"
Example 2:
Input: "abcd"
Output: ""
Note:
2 <= S.length <= 10^5
S consists of lowercase English letters.
*/
class Solution {
public:
string longestDupSubstring(string S) {
std::string_view longest;
std::unordered_set<std::string_view> set;
int start = 1;
int end = S.size() - 1;
while (start <= end)
{
int len = start + (end - start) / 2;
bool found = false;
for (int i = 0; i != S.size() - len + 1; ++i)
{
const auto [it, inserted] = set.emplace(S.data() + i, len);
if (!inserted)
{
found = true;
longest = *it;
break;
}
}
if (found)
start = len + 1;
else
end = len - 1;
set.clear();
}
return {longest.begin(), longest.end()};
}
};