Skip to content

Commit 1423d09

Browse files
authored
Create substrings-of-size-three-with-distinct-characters.cpp
1 parent 1fba8c5 commit 1423d09

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int countGoodSubstrings(string s) {
7+
static const int K = 3;
8+
9+
int result = 0;
10+
unordered_map<int, int> count;
11+
for (int i = 0; i < size(s); ++i) {
12+
if (i >= K) {
13+
if (--count[s[i - K]] == 0) {
14+
count.erase(s[i - K]);
15+
}
16+
}
17+
++count[s[i]];
18+
if (size(count) == K) {
19+
++result;
20+
}
21+
}
22+
return result;
23+
}
24+
};

0 commit comments

Comments
 (0)