class Solution:
def countGoodSubstrings(self, s: str) -> int:
count = 0
for i in range(len(s) - 2):
substring = s[i:i+3]
if len(set(substring)) == 3:
count += 1
return count
class Solution {
public:
int countGoodSubstrings(string s) {
int count = 0;
for (int i = 0; i + 2 < s.size(); ++i) {
if (s[i] != s[i+1] && s[i] != s[i+2] && s[i+1] != s[i+2]) {
count++;
}
}
return count;
}
};
class Solution {
public int countGoodSubstrings(String s) {
int count = 0;
for (int i = 0; i <= s.length() - 3; i++) {
char a = s.charAt(i), b = s.charAt(i+1), c = s.charAt(i+2);
if (a != b && a != c && b != c) {
count++;
}
}
return count;
}
}
var countGoodSubstrings = function(s) {
let count = 0;
for (let i = 0; i <= s.length - 3; i++) {
let a = s[i], b = s[i+1], c = s[i+2];
if (a !== b && a !== c && b !== c) {
count++;
}
}
return count;
};
s
, you are asked to count the number of substrings of length 3 that consist of all distinct characters. In other words, for every substring of size 3, check if all the characters are different, and count how many such substrings exist.
s
consists of lowercase English letters.s
and check if they're all different. The most straightforward way is to check each possible substring of length 3.
At first, you might think of generating all substrings, but since we only care about those of length 3, we can just slide a window of size 3 across the string. For each window, check if the three characters are unique.
A brute-force approach would be to extract every substring and check for uniqueness by comparing each character. But we can optimize by noting that for just 3 characters, it's easy to compare them directly without extra data structures.
If s
is very long, we want to avoid unnecessary work. Luckily, checking three characters is constant time, so our sliding window approach is efficient.
len(s) - 3 + 1
(so that each window is of size 3).a != b && a != c && b != c
).s = "xyzzaz"
.