[LeetCode] 1100. Find K-Length Substrings With No Repeated Characters

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

长度为 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 }

 

sliding window相关题目

LeetCode 题目总结

posted @ 2020-07-20 05:29  CNoodle  阅读(204)  评论(0编辑  收藏  举报