Leetcode - Find K-Length Substrings With No Repeated Characters
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
}
评论 (0)