Leetcode - Length of Longest Fibonacci Subsequence
Leetcode - Minimum Window Substring

Leetcode - Find K-Length Substrings With No Repeated Characters

violet posted @ May 15, 2020 05:07:20 AM in 算法 with tags Algorithm Golang SlidingWindow , 332 阅读

https://leetcode.com/problems/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.

 

func numKLenSubstrNoRepeats(S string, K int) int {
    if len(S) < K {
        return 0
    }
    hash := map[byte]int{}
    i := 0
    j := i
    count := 0
    for j < len(S) {
        
        for j < len(S) && j - i + 1 <= K {
            if _, ok := hash[S[j]]; !ok {
                hash[S[j]]++
            } else {
                break
            }
            j++
        }
        
        if len(hash) == K {
            count++
            
        }
        delete(hash, S[i])
        i++
    }
    return count
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter