LeetCode in Kotlin

3853. Merge Close Characters

Medium

You are given a string s consisting of lowercase English letters and an integer k.

Two equal characters in the current string s are considered close if the distance between their indices is at most k.

When two characters are close, the right one merges into the left. Merges happen one at a time, and after each merge, the string updates until no more merges are possible.

Return the resulting string after performing all possible merges.

Note: If multiple merges are possible, always merge the pair with the smallest left index. If multiple pairs share the smallest left index, choose the pair with the smallest right index.

Example 1:

Input: s = “abca”, k = 3

Output: “abc”

Explanation:

Example 2:

Input: s = “aabca”, k = 2

Output: “abca”

Explanation:

Example 3:

Input: s = “yybyzybz”, k = 2

Output: “ybzybz”

Explanation:

Constraints:

Solution

class Solution {
    fun mergeCharacters(s: String, k: Int): String {
        val result = StringBuilder()
        result.ensureCapacity(s.length)
        val cnt = IntArray(26)
        for (t in 0..<s.length) {
            val c = s[t]
            val idx = c.code - 'a'.code
            if (cnt[idx] > 0) {
                continue
            }
            result.append(c)
            cnt[idx]++
            if (result.length > k) {
                val drop = result[result.length - k - 1]
                cnt[drop.code - 'a'.code]--
            }
        }
        return result.toString()
    }
}