Easy
LABSubstrings of Size Three with Distinct Characters
Return the number of length-3 substrings with three distinct characters.
EXAMPLES
Example 1
Input
{
"s": "xyzzaz"
}
Output
1FUNCTION SHAPE
s: string→intSOLUTION NOTE
Window: Counter(). Valid: len(freq) == 3 (because the substring has fixed length 3, if we have a counter of length 3, this means we have no repeated chars).
Reveal reference solution +
pythonREFERENCE
def countGoodSubstrings(self, s: str) -> int:
freq = Counter()
n = len(s)
res = 0
k = 3
for i in range(n):
freq[s[i]] += 1
if i >= k - 1:
if len(freq) == 3: # no repeated chars
res += 1
freq[s[i-(k-1)]] -= 1
if freq[s[i-(k-1)]] == 0:
del freq[s[i-(k-1)]]
return resTime
O(n)Space
O(1)