LeetCode in Kotlin

3561. Resulting String After Adjacent Removals

Medium

You are given a string s consisting of lowercase English letters.

You must repeatedly perform the following operation while the string s has at least two consecutive characters:

Return the resulting string after no more operations can be performed.

Note: Consider the alphabet as circular, thus 'a' and 'z' are consecutive.

Example 1:

Input: s = “abc”

Output: “c”

Explanation:

Example 2:

Input: s = “adcb”

Output: “”

Explanation:

Example 3:

Input: s = “zadb”

Output: “db”

Explanation:

Constraints:

Solution

class Solution {
    fun resultingString(s: String): String {
        val n = s.length
        var p = 0
        val buf = CharArray(n)
        for (c in s.toCharArray()) {
            if (p > 0) {
                val d = buf[p - 1].code - c.code
                val ad = if (d < 0) -d else d
                if (ad == 1 || ad == 25) {
                    p--
                    continue
                }
            }
            buf[p++] = c
        }
        return String(buf, 0, p)
    }
}