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 = "havefunonleetcode", k = 5
Output: 6
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.
Constraints:
1 <= s.length <= 104
s consists of lowercase English letters.
1 <= k <= 104
Solutions
Solution 1: Sliding Window + Hash Table
We maintain a sliding window of length \(k\), and use a hash table \(cnt\) to count the occurrences of each character in the window.
First, we add the first \(k\) characters of the string \(s\) to the hash table \(cnt\), and check whether the size of \(cnt\) is equal to \(k\). If it is, it means that all characters in the window are different, and the answer \(ans\) is incremented by one.
Next, we start to traverse the string \(s\) from \(k\). Each time we add \(s[i]\) to the hash table \(cnt\), and at the same time subtract \(s[i-k]\) from the hash table \(cnt\) by one. If \(cnt[s[i-k]]\) is equal to \(0\) after subtraction, we remove \(s[i-k]\) from the hash table \(cnt\). If the size of the hash table \(cnt\) is equal to \(k\) at this time, it means that all characters in the window are different, and the answer \(ans\) is incremented by one.
Finally, return the answer \(ans\).
The time complexity is \(O(n)\), and the space complexity is \(O(\min(k, |\Sigma|))\), where \(n\) is the length of the string \(s\); and \(\Sigma\) is the character set, in this problem the character set is lowercase English letters, so \(|\Sigma| = 26\).