@Design_Gurus
Eventually, that can give the correct answer for this kind of question. But during the process, the window could have more than 4 types of character and maxRepeatLetterCount
also will be a mess.
In the below case( str = [a a b c d e], k = 2), at 5 round, it will jump into if (windowEnd - windowStart + 1 - maxRepeatLetterCount > k)
, start
will be 0 -> 1.
Because the leftChar is a
, a
also will be removed from the window, current maxRepeatLetterCount
obviously should be 1, but if use if
, the maxRepeatLetterCount
is still 2. So I think here need to use while
and re-calculate the maxRepeatLetterCount
to give the correct maxRepeatLetterCount
.
1.
start
↓
[a] a b c d e
↑
end
- hashMap = [a->1]
- maxRepeatLetterCount = 1
- condition:
(windowEnd - windowStart + 1 - maxRepeatLetterCount) > k
0 - 0 + 1 - 1 = 0
- maxLength = 1
2.
[a a] b c d e
- hashMap = [a->2]
- maxRepeatLetterCount = 2
- condition:
(windowEnd - windowStart + 1 - maxRepeatLetterCount) > k
1 - 0 + 1 - 2 = 0
- maxLength = 2
3.
[a a b] c d e
- hashMap = [a->2, b->1]
- maxRepeatLetterCount = 2
- condition:
(windowEnd - windowStart + 1 - maxRepeatLetterCount) > k
2 - 0 + 1 - 2 = 1
- maxLength = 3
4.
[a a b c] d e
- hashMap = [a->2, b->1, c->1]
- maxRepeatLetterCount = 2
- condition:
(windowEnd - windowStart + 1 - maxRepeatLetterCount) > k
3 - 0 + 1 - 2 = 2
- maxLength = 4
5.
[a a b c d] e
- hashMap = [a->2, b->1, c->1, d->1]
- maxRepeatLetterCount = 2 (<- a)
- condition:
(windowEnd - windowStart + 1 - maxRepeatLetterCount) > k
4 - 0 + 1 - 2 = 3 > k
- leftChar: a
hashMap = [a->1, b->1, c->1, d->1]
windowStart = 1 ===> a [a b c d] e
maxRepeatLetterCount = 1 (because `a` has been removed)
- maxLength = 4