You are viewing a single comment's thread. Return to all comments →
O(n) solution in Scala:
import scala.collection.immutable val closeOf = immutable.Map('{' -> '}', '(' -> ')', '[' -> ']') def isBalanced(s: String): String = { val (result, open) = s.foldLeft((true, immutable.List[Char]())) { case ((false, _), _) => (false, Nil) case ((true, open), chr) => chr match { case '{' | '(' | '[' => (true, chr :: open) case '}' | ')' | ']' if open.nonEmpty => if (closeOf(open.head) == chr) (true, open.tail) else (false, Nil) case _ => (false, Nil) } } if (result && open.isEmpty) "YES" else "NO" }
Seems like cookies are disabled on this browser, please enable them to open this website
Balanced Brackets
You are viewing a single comment's thread. Return to all comments →
O(n) solution in Scala: