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.counteris the duplicate counter,resis the resulting number of substrings that have unique characters, andmis a map that is used to find out whether a character is a duplicate. - Then we loop from
0toK - 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]] == 2we have to add one tocounterbecausecountercounts the number of duplicates.
- Inside that loop, we add one to
- After we have done the first
Kelements, 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
Ktolen(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 subtract1fromcounterbecause 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
1tom[S[i]]. Ifm[S[i]] == 2we know that there is a duplicate so we add1tocounter. - After adding and subtracting from
counter, we can check whethercounter == 0. We do this because ifcounter == 0, there are no duplicates. So ifcounter == 0we can add1tores.
- 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