1876. Substrings of Size Three with Distinct Characters LeetCode Solution
In this guide, you will get 1876. Substrings of Size Three with Distinct Characters LeetCode Solution with the best time and space complexity. The solution to Substrings of Size Three with Distinct Characters problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Substrings of Size Three with Distinct Characters solution in C++
- Substrings of Size Three with Distinct Characters solution in Java
- Substrings of Size Three with Distinct Characters solution in Python
- Additional Resources
Problem Statement of Substrings of Size Three with Distinct Characters
A string is good if there are no repeated characters.
Given a string s, return the number of good substrings of length three in s.
Note that if there are multiple occurrences of the same substring, every occurrence should be counted.
A substring is a contiguous sequence of characters in a string.
Example 1:
Input: s = “xyzzaz”
Output: 1
Explanation: There are 4 substrings of size 3: “xyz”, “yzz”, “zza”, and “zaz”.
The only good substring of length 3 is “xyz”.
Example 2:
Input: s = “aababcabc”
Output: 4
Explanation: There are 7 substrings of size 3: “aab”, “aba”, “bab”, “abc”, “bca”, “cab”, and “abc”.
The good substrings are “abc”, “bca”, “cab”, and “abc”.
Constraints:
1 <= s.length <= 100
s consists of lowercase English letters.
Complexity Analysis
- Time Complexity:
- Space Complexity:
1876. Substrings of Size Three with Distinct Characters LeetCode Solution in C++
class Solution {
public:
int countGoodSubstrings(string s) {
int ans = 0;
for (int i = 0; i + 2 < s.length(); ++i) {
const char a = s[i];
const char b = s[i + 1];
const char c = s[i + 2];
if (a == b || a == c || b == c)
continue;
++ans;
}
return ans;
}
};
/* code provided by PROGIEZ */
1876. Substrings of Size Three with Distinct Characters LeetCode Solution in Java
class Solution {
public int countGoodSubstrings(String s) {
int ans = 0;
for (int i = 0; i < s.length() - 2; ++i) {
final char a = s.charAt(i);
final char b = s.charAt(i + 1);
final char c = s.charAt(i + 2);
if (a == b || a == c || b == c)
continue;
++ans;
}
return ans;
}
}
// code provided by PROGIEZ
1876. Substrings of Size Three with Distinct Characters LeetCode Solution in Python
class Solution:
def countGoodSubstrings(self, s: str) -> int:
ans = 0
for a, b, c in zip(s, s[1:], s[2:]):
if a == b or a == c or b == c:
continue
ans += 1
return ans
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.