< Ace Coding /> 🚀
Question Description
Given a string s and an integer k, return the number of substrings in s of length k with no repeated characters.
Example 1:
Input: s = "unonleetcode", k = 5
Output: 2
Explanation: There are 6 substrings they are: 'havef','avefu','vefun','efuno','etcod','tcode'.
Example 2:
Input: s = "home", k = 5
Output: 0
Explanation: Notice k can be larger than the length of s. In this case, it is not possible to find any substring.
Example 3:
Input: s = "havefunonleetcode", k = 5
Output: 6
Explanation: There are 6 substrings they are: 'havef','avefu','vefun','efuno','etcod','tcode'.
✅ Solution: as I have told you this pattern repeats a lot so you got this
def subStringK(s, k):
seen = set()
count = 0
l = 0
for r in range(len(s)):
if s[r] in seen:
while s[l] != s[r]:
seen.remove(s[l])
l += 1
l += 1
if r - l + 1 == k:
count += 1
seen.remove(s[l])
l += 1
seen.add(s[r])
return count
print(subStringK("unonleetcode", 5))
print(subStringK("havefunonleetcode", 5))
print(subStringK("aaabbaaa", 2))
print(subStringK("aaabbaaa", 100))
3 · 356 ·