forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
number-of-substrings-containing-all-three-characters.cpp
63 lines (60 loc) · 1.69 KB
/
number-of-substrings-containing-all-three-characters.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
// Time: O(n)
// Space: O(1)
class Solution {
public:
int numberOfSubstrings(string s) {
int result = 0;
vector<int> left(3, -1);
for (int right = 0; right < s.length(); ++right) {
left[s[right] - 'a'] = right;
result += *min_element(cbegin(left), cend(left)) + 1;
}
return result;
}
};
// Time: O(n)
// Space: O(1)
class Solution2 {
public:
int numberOfSubstrings(string s) {
int result = 0, left = 0;
vector<int> count(3);
for (int right = 0; right < s.length(); ++right) {
++count[s[right] - 'a'];
while (all_of(cbegin(count), cend(count),
[](const auto& x) {
return x != 0;
})) {
--count[s[left++] - 'a'];
}
result += left;
}
return result;
}
};
// Time: O(n)
// Space: O(1)
class Solution3 {
public:
int numberOfSubstrings(string s) {
int result = 0, right = 0;
vector<int> count(3);
for (int left = 0; left < s.length(); ++left) {
while (right < s.length() &&
!all_of(cbegin(count), cend(count),
[](const auto& x) {
return x != 0;
})) {
++count[s[right++] - 'a'];
}
if (all_of(cbegin(count), cend(count),
[](const auto& x) {
return x != 0;
})) {
result += (s.length() - 1) - (right - 1) + 1;
}
--count[s[left] - 'a'];
}
return result;
}
};