leetcode 1358 - Number of Substrings Containing All Three Characters

https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/

Given a string s consisting only of characters a, b and c.

Return the number of substrings containing at least one occurrence of all these characters a, b and c.

Example 1:

Input: s = “abcabc”
Output: 10
Explanation: The substrings containing at least one occurrence of the characters a, b and c are “abc”, “abca”, “abcab”, “abcabc”, “bca”, “bcab”, “bcabc”, “cab”, “cabc” and “abc” (again).
Example 2:

Input: s = “aaacb”
Output: 3
Explanation: The substrings containing at least one occurrence of the characters a, b and c are “aaacb”, “aacb” and “acb”.
Example 3:

Input: s = “abc”
Output: 1

Constraints:

3 <= s.length <= 5 x 10^4
s only consists of a, b or c characters.

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
class Solution {
public:
int numberOfSubstrings(string s) {
int size = s.size();

return ((long)size * (size + 1)) / 2 - noneABC(s);
}

int noneABC(string &s) {
int size = s.size();
vector<int> count(3, 0);
int total = 0;

int i = 0;
for (int j = 0; j < size; j++) {
int k = s[j] - 'a';
count[k]++;

while (count[0] >= 1 && count[1] >= 1 && count[2] >= 1) {
k = s[i++] - 'a';
count[k]--;
}

total += j - i + 1;
}

return total;
}
};

class Solution {
public:
int numberOfSubstrings(string s) {
int size = s.size();
int total = 0;

int count[3] = {0, 0, 0};
int i = 0;
for (int j = 0; j < size; j++) {
int k = s[j] - 'a';
count[k]++;

while (count[0] && count[1] && count[2]) {
k = s[i++] - 'a';
count[k]--;
}

total += i;
}

return total;
}
};