File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
longest-repeating-character-replacement Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ fun characterReplacement (s : String , k : Int ): Int {
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 ))
6
+ var ans = 0
7
+ var i = 0
8
+ 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
+ }
17
+ while (j != s.length) {
18
+ val diff = j - i - queue.peek().first()
19
+ if (diff > k) {
20
+ break
21
+ }
22
+ val d = s[j].code - ' A' .code
23
+ if (diff == k && queue.peek().first() != cnts[d]) {
24
+ break
25
+ }
26
+ j++
27
+ queue.offer(listOf (++ cnts[d], d)) // O(logn)
28
+ }
29
+ ans = maxOf(ans, j - i)
30
+ val d = s[i++ ].code - ' A' .code
31
+ queue.offer(listOf (-- cnts[d], d)) // O(logn)
32
+ }
33
+ return ans
34
+ }
35
+ }
You can’t perform that action at this time.
0 commit comments