Substrings of Size Three with Distinct Characters
A string is good if there are no repeated characters. Given string s, return the number of good substrings of length exactly 3.
Example 1
Input: "xyzzaz" → Output: 1 (only "xyz" is good)
Example 2
Input: "aababcabc" → Output: 4
Solution Approach
Slide a window of fixed size 3, check if all 3 characters are distinct.
- Iterate i from 0 to n-3.
- Extract s[i], s[i+1], s[i+2].
- If all three are distinct (s[i]!=s[i+1] && s[i+1]!=s[i+2] && s[i]!=s[i+2]): count++.
Java
class Solution {
public int countGoodSubstrings(String s) {
int count = 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) count++;
}
return count;
}
}
- Time Complexity: O(N)
- Space Complexity: O(1)