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

1 Answer

0 votes
object Main {

  def removeAdjacentDuplicates(s: String): String = {
    val stack = scala.collection.mutable.ArrayBuffer[Char]()

    for (ch <- s) {
      if (stack.nonEmpty && stack.last == ch)
        stack.remove(stack.length - 1)   // pop
      else
        stack.append(ch)                 // push
    }

    stack.mkString
  }

  def main(args: Array[String]): Unit = {
    val s = "abbacccada"
    
    println(removeAdjacentDuplicates(s))   
  }
}




/*
run:

cada

*/

 



answered Mar 7 by avibootz

Related questions

...