[LeetCode] Number of Substrings Containing All Three Characters

1358. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int numberOfSubstrings(string s) {
int res = 0, n = s.length(), l = 0;
unordered_map<char, int> freq;

for(int i = 0; i < n; i++) {
freq[s[i]]++;

while(freq[s[l]] > 1) {
freq[s[l++]]--;
}

if(min({freq['a'], freq['b'], freq['c']}) == 1) {
res += l + 1;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/01/PS/LeetCode/number-of-substrings-containing-all-three-characters/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.