[LeetCode] 1100. Find K-Length Substrings With No Repeated Characters
阿新 • • 發佈:2020-07-20
Given a stringS
, return the number of substrings of lengthK
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 }