File tree Expand file tree Collapse file tree 1 file changed +6
-14
lines changed
longest-repeating-character-replacement Expand file tree Collapse file tree 1 file changed +6
-14
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
fun characterReplacement (s : String , k : Int ): Int {
3
3
val cnts = MutableList <Int >(' Z' .code - ' A' .code + 1 ) {0 }
4
- val queue = PriorityQueue <List <Int >>() {a, b -> b.first() - a.first()}
5
- queue.offer(listOf (0 , - 1 ))
4
+ var max_cnt = 0
6
5
var ans = 0
7
6
var i = 0
8
7
var j = 0
9
- while (j != s.length) { // T(n) = S(n) = O(nlogn)
10
- while (queue.size > 1 ) {
11
- val u = queue.peek()
12
- if (u.first() == cnts[u.last()]) {
13
- break
14
- }
15
- queue.poll()
16
- }
8
+ while (j != s.length) { // T(n) = S(n) = O(n)
17
9
while (j != s.length) {
18
- val diff = j - i - queue.peek().first()
10
+ val diff = j - i - max_cnt
19
11
if (diff > k) {
20
12
break
21
13
}
22
14
val d = s[j].code - ' A' .code
23
- if (diff == k && queue.peek().first() != cnts[d]) {
15
+ if (diff == k && max_cnt != cnts[d]) {
24
16
break
25
17
}
26
18
j++
27
- queue.offer( listOf ( ++ cnts[d], d)) // O(logn )
19
+ max_cnt = maxOf(max_cnt, ++ cnts[d])
28
20
}
29
21
ans = maxOf(ans, j - i)
30
22
val d = s[i++ ].code - ' A' .code
31
- queue.offer( listOf ( -- cnts[d], d)) // O(logn)
23
+ cnts[d]--
32
24
}
33
25
return ans
34
26
}
You can’t perform that action at this time.
0 commit comments