Given a string S
, return the number of substrings 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 is not possible to find any substring.
Note:
1 <= S.length <= 10^4
- All characters of S are lowercase English letters.
1 <= K <= 10^4
长度为 K 的无重复字符子串。又是滑动窗口类型的题。但是这个题问的是长度只能是exact K个字符,既不是至多也不是至少。可以用76题的模板做但是需要注意一些细节。
时间O(n)
空间O(n) - hashset
Java实现
1 class Solution { 2 public int numKLenSubstrNoRepeats(String S, int K) { 3 // corner case 4 int len = S.length(); 5 if (len < K) { 6 return 0; 7 } 8 9 // normal case 10 int start = 0; 11 int end = 0; 12 int res = 0; 13 HashSet<Character> set = new HashSet<>(); 14 while (end < len) { 15 while (set.contains(S.charAt(end))) { 16 set.remove(S.charAt(start)); 17 start++; 18 } 19 set.add(S.charAt(end)); 20 end++; 21 if (end - start == K) { 22 res++; 23 set.remove(S.charAt(start)); 24 start++; 25 } 26 } 27 return res; 28 } 29 }