Substrings of Size Three with Distinct Characters
Problem
Return the number of length-3 substrings of s with three distinct characters.
s = "xyzzaz"1def count_good_substrings(s):
cnt = 0
for i in range(len(s) - 2):
a, b, c = s[i], s[i+1], s[i+2]
if a != b and b != c and a != c:
cnt += 1
return cnt
function countGoodSubstrings(s) {
let cnt = 0;
for (let i = 0; i + 2 < s.length; i++) {
if (s[i] !== s[i+1] && s[i+1] !== s[i+2] && s[i] !== s[i+2]) cnt++;
}
return cnt;
}
class Solution {
public int countGoodSubstrings(String s) {
int cnt = 0;
for (int i = 0; i + 2 < s.length(); i++) {
char a = s.charAt(i), b = s.charAt(i+1), c = s.charAt(i+2);
if (a != b && b != c && a != c) cnt++;
}
return cnt;
}
}
int countGoodSubstrings(string s) {
int cnt = 0;
for (int i = 0; i + 2 < (int)s.size(); i++) {
if (s[i] != s[i+1] && s[i+1] != s[i+2] && s[i] != s[i+2]) cnt++;
}
return cnt;
}
Explanation
The window size is fixed at three, so there is no fancy bookkeeping needed. We just look at every group of three neighboring characters and check whether all three are different.
We slide an index i from the start to len(s) - 3. At each spot the three characters are a = s[i], b = s[i+1], and c = s[i+2].
They are all distinct exactly when a != b, b != c, and a != c all hold. Checking those three pairwise comparisons is enough — if any two match, the substring is not good.
Every time all three differ, we add one to cnt, and that running total is the answer.
Example: s = "xyzzaz". The windows are "xyz" (all different, count it), "yzz", "zza", and "zaz" (each has a repeat). Only one qualifies, so the answer is 1.