3 minutes
Leetcode 1100
1100. Find K-Length Substrings With No Repeated Characters
The Idea Of This Solution:
This solution aims to use a counter called counter
to count the number of duplicates. Also, when counter == 0
, the substring has no duplicates.
How This Solution Works:
- First, we make the variables
counter
,res
, andm
.counter
is the duplicate counter,res
is the resulting number of substrings that have unique characters, andm
is a map that is used to find out whether a character is a duplicate. - Then we loop from
0
toK - 1
.- Inside that loop, we add one to
m[S[i]]
(We are adding one to the character counter). - After adding one to
m[S[i]]
we can check whetherm[S[i]] == 2
(We are checking whether there is a duplicate). Ifm[S[i]] == 2
we have to add one tocounter
becausecounter
counts the number of duplicates.
- Inside that loop, we add one to
- After we have done the first
K
elements, we can check whethercounter == 0
. If so, we can add one tores
. Ifcounter == 0
, we know that there are no duplicates. - Then we can loop from
K
tolen(S)
.- Inside that loop, we remove the first element of the substring from
m
, and then we check whetherm[first letter of substring] == 1
. If so, we can subtract1
fromcounter
because when the frequency of a letter is1
, we know that it is not a duplicate. - Next, we make the letter after the end of the substring the new end of the substring and add
1
tom[S[i]]
. Ifm[S[i]] == 2
we know that there is a duplicate so we add1
tocounter
. - After adding and subtracting from
counter
, we can check whethercounter == 0
. We do this because ifcounter == 0
, there are no duplicates. So ifcounter == 0
we can add1
tores
.
- Inside that loop, we remove the first element of the substring from
The Code:
func numKLenSubstrNoRepeats(S string, K int) int {
if K > len(S) {
return 0
}
counter, res, m := 0, 0, make(map[uint8]int)
for i := 0; i < K; i++ {
m[S[i]]++
if m[S[i]] == 2 { counter++ }
}
if counter == 0 { res++ }
for i := K; i < len(S); i++ {
m[S[i-K]]--
if m[S[i-K]] == 1 { counter-- }
m[S[i]]++
if m[S[i]] == 2 { counter++ }
if counter == 0 {res++ }
}
return res
}
If You Don’t Like The Top Solutions Format:
func numKLenSubstrNoRepeats(S string, K int) int {
if K > len(S) {
return 0
}
counter, res, m := 0, 0, make(map[uint8]int)
for i := 0; i < K; i++ {
m[S[i]]++
if m[S[i]] == 2 {
counter++
}
}
if counter == 0 {
res++
}
for i := K; i < len(S); i++ {
m[S[i-K]]--
if m[S[i-K]] == 1 {
counter--
}
m[S[i]]++
if m[S[i]] == 2 {
counter++
}
if counter == 0 {
res++
}
}
return res
}
Read other posts