Substrings of Size Three with Distinct Characters Problem
Description
LeetCode Problem 1876.
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 <= 100sconsists of lowercase English letters.
Solution
Approach: Sliding Window
Keep a window with no repeated letters, tracked by a 26-bit mask. For each right end r, shrink from the left until s[r] is not in the window, then add it. If the window has at least 3 letters, the substring of length 3 ending at r is good.
Because the substring has fixed length 3, you can also just compare each triple of neighbours directly; the window version extends to any length k.
Complexity: O(n) time, O(1) space, where n is the length of s.
class Solution:
def countGoodSubstrings(self, s: str) -> int:
ans = mask = l = 0
for r, x in enumerate(map(lambda c: ord(c) - 97, s)):
while mask >> x & 1:
y = ord(s[l]) - 97
mask ^= 1 << y
l += 1
mask |= 1 << x
ans += int(r - l + 1 >= 3)
return ans