zoukankan      html  css  js  c++  java
  • 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

    sliding window

    1. first store the first leftmost K-length substring in a hashTable or array of frequencies

    2. then iterate through the rest of characters and erase the first element and add the next element from the right. if in the hashTable we have K different character we add 1 to the counter. after that return as answer the counter

    time = O(n), space = O(1)

    class Solution {
        public int numKLenSubstrNoRepeats(String S, int K) {
            if(K > S.length()) {
                return 0;
            }
            Set<Character> set = new HashSet<>();
            int slow = 0, fast = 0, counter = 0;
            while(fast < S.length()) {
                while(!set.add(S.charAt(fast))) {
                    set.remove(S.charAt(slow++));
                }
                fast++;
                if(set.size() > K) {
                    set.remove(S.charAt(slow++));
                }
                if(set.size() == K) {
                    counter++;
                }
            }
            return counter;
        }
    }
  • 相关阅读:
    .NET 开源框架
    ORM 开发框架
    C# 文件下载四方法
    用ASP.net判断上传文件类型的三种方法
    站在十字路口的程序媛,该如何选择?
    突然的烦恼
    Request获取url信息的各种方法比较 及 Request.UrlReferrer详解
    JS 获得当前地址栏url
    MvcPager 概述
    Simditor使用方法
  • 原文地址:https://www.cnblogs.com/fatttcat/p/11386827.html
Copyright © 2011-2022 走看看