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

1 Answer

0 votes
import Foundation

func removeAdjacentDuplicates(_ s: String) -> String {
    var stack: [Character] = []
    stack.reserveCapacity(s.count)

    for ch in s {
        if let last = stack.last, last == ch {
            stack.removeLast()      // pop
        } else {
            stack.append(ch)        // push
        }
    }

    return String(stack)
}

let s = "abbacccada"

print(removeAdjacentDuplicates(s))   




/*
run:

cada

*/

 



answered Mar 7 by avibootz

Related questions

...