1100. Find K-Length Substrings With No Repeated Characters π
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 = "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 <= 104sconsists of lowercase English letters.1 <= k <= 104
Solutions
Solution 1: Sliding Window + Hash Table
Thinking
Checking every substring of length \(k\) for uniqueness costs \(O(nk)\). With \(n,k\le 10^4\) this can pass, yet adjacent windows differ by only one character entering and one leaving.
Maintain a window of length \(k\) and a frequency map: add \(s[i]\), drop \(s[i-k]\), and remove a key when its count hits zero. The map has exactly \(k\) keys if and only if every character in the window appears once, so that test increments the answer.
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\).
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | |