Scala: Make sure braces are balanced

后端 未结 3 622
不思量自难忘°
不思量自难忘° 2021-01-19 07:54

I am running a code to balance brackets in statement. I think i have gotten it correct but it is failing on one particular statement, i need to understand why?

This

3条回答
  •  孤独总比滥情好
    2021-01-19 07:56

    You can also use the property of Stack data structure to solve this problem. When you see open bracket, you push it into the stack. When you see close bracket, you pop from the stack (instead of Stack I'm using List, because immutable Stack is deprecated in Scala):

    def isBalanced(chars: Seq[Char]): Boolean = {
      import scala.annotation.tailrec
    
      case class BracketInfo(c: Char, idx: Int)
      def isOpen(c: Char): Boolean = c == '('
      def isClose(c: Char): Boolean = c == ')'
      def safePop[T](stack: List[T]): Option[T] = {
        if (stack.length <= 1) stack.headOption
        else stack.tail.headOption
      }
    
      @tailrec
      def isBalanced(chars: Seq[Char], idx: Int, stack: List[BracketInfo]): Boolean = {
        chars match {
          case Seq(c, tail@_*) =>
            val newStack = BracketInfo(c, idx) :: stack // Stack.push
            if (isOpen(c)) isBalanced(tail, idx + 1, newStack)
            else if (isClose(c)) {
              safePop(stack) match {
                case Some(b) => isBalanced(tail, idx + 1, stack.tail)
                case None =>
                  println(s"Closed bracket '$c' at index $idx was not opened")
                  false
              }
            }
            else isBalanced(tail, idx + 1, stack)
          case Seq() =>
            if (stack.nonEmpty) {
              println("Stack is not empty => there are non-closed brackets at positions: ")
              println(s"${stack.map(_.idx).mkString(" ")}")
            }
            stack.isEmpty
        }
      }
    
      isBalanced(chars, 0, List.empty[BracketInfo])
    }
    

提交回复
热议问题