1100. Find K-Length Substrings With No Repeated Characters - Medium

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;
    }
}

 

转载于:https://www.cnblogs.com/fatttcat/p/11386827.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值