LeetCode Entry

Remove All Adjacent Duplicates In String

10.11.2022 easy 2022

Just scan symbols one by one and remove duplicates from the end.

https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/ easy

Solution:


    fun removeDuplicates(s: String): String {
        val stack = Stack<Char>()
        s.forEach { c ->
            if (stack.isNotEmpty() && stack.peek() == c) {
                stack.pop()
            } else {
                stack.push(c)
            }
        }
        return stack.joinToString("")
    }

Explanation: Just scan symbols one by one and remove duplicates from the end. Complexity: O(N) Memory: O(N)