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


    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. 1 <= S.length <= 10^4
    2. All characters of S are lowercase English letters.
    3. 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 }

    sliding window相关题目

    LeetCode 题目总结

  • 相关阅读:
    日志配置
    Mybaties核心配置文件
    配置3
    写了两个数据获得方式----费劲周折
    applicationContext
    配置2
    Django-缓存的配置
    RabbitMQ的工作模式
    centos下保留python2安装python3
    python位运算
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13343078.html
Copyright © 2020-2023  润新知