Leetcode 1876. Substrings of Size Three with Distinct Characters
You are given a string s
of length n
. Your task is to find the number of substrings of length 3 that consist of distinct characters.
Example 1:
Input: s = "xyzzaz"
Output: 1
Explanation: There is only one substring of size 3 with distinct characters: "xyz".
Example 2:
Input: s = "aababcabc"
Output: 4
Explanation: Substrings with 3 unique characters are "abc", "bca", "cab" and "abc".
n
of the input string?#include <iostream>
#include <unordered_set>
int countGoodSubstrings(std::string s) {
if (s.length() < 3) return 0;
int count = 0;
for (int i = 0; i <= s.length() - 3; ++i) {
std::unordered_set<char> unique_chars(s.begin() + i, s.begin() + i + 3);
if (unique_chars.size() == 3) {
++count;
}
}
return count;
}
int main() {
// Test cases
std::string s1 = "xyzzaz";
std::string s2 = "aababcabc";
std::cout << "Count for s1: " << countGoodSubstrings(s1) << std::endl;
std::cout << "Count for s2: " << countGoodSubstrings(s2) << std::endl;
return 0;
}
Initial Checks: If the string length is less than 3, return 0 because no substring of size 3 is possible.
length - 3
. For each iteration:
n
is the length of the string. We are iterating through the string once and performing a fixed amount of work (3 insertions into a set) at each step.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?