Skip to content

Instantly share code, notes, and snippets.

@codecakes
Created September 26, 2022 13:57
Show Gist options
  • Save codecakes/17c66556b0af5edf33f5fe7ed0ab1fe9 to your computer and use it in GitHub Desktop.
Save codecakes/17c66556b0af5edf33f5fe7ed0ab1fe9 to your computer and use it in GitHub Desktop.
Longest Repeating Character with Replacement
// This isn't the most optimal kotlin code. but it is one that solves all cases.
class Solution {
fun characterReplacement(s: String, k: Int): Int {
val n = s.length
val maxCharMap = mutableMapOf<Char, Int>();
var left = 0
var maxCount = Float.NEGATIVE_INFINITY.toInt()
var newMax = maxCount
var maxLen = maxCount
var char: Char? = null;
var strLen: Int = 0
var minCharFlip: Int = 0
for (right in 0..n-1) {
char = s[right]
strLen = right.minus(left) + 1
maxCharMap.put(char, maxCharMap.getOrDefault(char, 0) + 1)
newMax = (
maxOf(
maxCount,
maxCharMap.getOrElse(char) { 0 }
)
)
minCharFlip = strLen.minus(newMax)
when (minCharFlip > k) {
true -> {
maxCharMap.put(
s[left], maxCharMap.getOrDefault(s[left], 0) - 1)
left++
strLen = right.minus(left).plus(1)
maxCharMap.forEach { (key, value) ->
maxCount = maxOf(maxCount, value)
}
}
else -> maxCount = newMax
}
maxLen = maxOf(maxLen, strLen)
}
return maxLen
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment