首页 > 其他 > 详细

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

时间:2019-08-21 09:39:06      阅读:143      评论:0      收藏:0      [点我收藏+]

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

 

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

原文:https://www.cnblogs.com/fatttcat/p/11386827.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!