-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathcount-residue-prefixes.cpp
More file actions
44 lines (42 loc) · 975 Bytes
/
count-residue-prefixes.cpp
File metadata and controls
44 lines (42 loc) · 975 Bytes
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
// Time: O(n + 26)
// Space: O(26)
// hash table
class Solution {
public:
int residuePrefixes(string s) {
int result = 0;
vector<bool> lookup(26);
for (int i = 0, distinct = 0; i < size(s); ++i) {
if (!lookup[s[i] - 'a']) {
if (++distinct >= 3) {
break;
}
}
lookup[s[i] - 'a'] = true;
if (distinct == (i + 1) % 3) {
++result;
}
}
return result;
}
};
// Time: O(n)
// Space: O(3)
// hash table
class Solution2 {
public:
int residuePrefixes(string s) {
int result = 0;
unordered_set<int> lookup;
for (int i = 0; i < size(s); ++i) {
lookup.emplace(s[i]);
if (size(lookup) >= 3) {
break;
}
if (size(lookup) == (i + 1) % 3) {
++result;
}
}
return result;
}
};