Leetcode 1876. Substrings of Size Three with Distinct Characters
You are given a string s
, and you need to return the number of good substrings of length three. A “good substring” is defined as a substring where all characters are distinct.
Example:
Input: s = "xyzzaz"
Output: 1
Explanation: There are four substrings of size 3: "xyz", "yzz", "zza", and "zaz".
"xyz" is the only good substring.
s
?
s
can be between 1 and 100, so we’ll consider this in our approach to ensure it runs efficiently even at the upper limit.s
is less than 3?
We will use a sliding window approach to solve this problem efficiently:
s
using a window of size 3.public class Solution {
public int countGoodSubstrings(String s) {
if (s.length() < 3) {
return 0;
}
int count = 0;
for (int i = 0; i <= s.length() - 3; i++) {
if (isGoodSubstring(s.substring(i, i + 3))) {
count++;
}
}
return count;
}
private boolean isGoodSubstring(String substring) {
return substring.charAt(0) != substring.charAt(1) &&
substring.charAt(1) != substring.charAt(2) &&
substring.charAt(0) != substring.charAt(2);
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.countGoodSubstrings("xyzzaz")); // Output: 1
System.out.println(sol.countGoodSubstrings("aababcabc")); // Output: 4
}
}
s
. We iterate through the string once and check each window in constant time.This ensures that our solution is efficient and works within given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?