zoukankan      html  css  js  c++  java
  • [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 题目总结

  • 相关阅读:
    XML&nbsp; XmlDocument
    程序集报错
    程序打开网页
    写入文件txt
    读取文件txt
    MSM8953中Android系统添加启动脚本.rc文件
    SELinux基础知识
    嵌入式Linux设备查看USB相关信息
    Linux内核态文件读写相关函数API
    C语言中sscanf()函数相关用法
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13343078.html
Copyright © 2011-2022 走看看