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;
        }
    }
  • 相关阅读:
    公有云数据库服务的申请与使用
    linux集群
    shell基础知识
    LNMP环境配置
    LAMP环境搭建与配置
    12月17日linux学习
    12月16日linux学习(文档的压缩与打包)
    12月13、14号linux学习
    12月12日linux学习
    目录结构
  • 原文地址:https://www.cnblogs.com/fatttcat/p/11386827.html
Copyright © 2011-2022 走看看