How to remove all adjacent duplicate characters from a string until no more can be removed in Kotlin

1 Answer

0 votes
fun removeAdjacentDuplicates(s: String): String {
    val stack = StringBuilder()

    for (ch in s) {
        val n = stack.length
        if (n > 0 && stack[n - 1] == ch) {
            stack.deleteCharAt(n - 1)   // pop
        } else {
            stack.append(ch)           // push
        }
    }

    return stack.toString()
}

fun main() {
    val s = "abbacccada"
    
    println(removeAdjacentDuplicates(s))   
}




/*
run:

cada

*/

 



answered Mar 7 by avibootz

Related questions

...