Skip to content

Commit 3f9d472

Browse files
authored
longest repeating character replacement solution
1 parent 6ece05d commit 3f9d472

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+
}

0 commit comments

Comments
 (0)