I have recently interview for scala. The question is to solve whether the given string is having balanced brackets or not.
For example, "(({[]}))" is balanced where "((({)}))" is not.
I have provided below solution -
object BalancedBrackets {
def main(a: Array[String]): Unit = {
println(balancedBrackets("((()))"))
}
def balancedBrackets(s: String): Boolean = {
import scala.collection.mutable.Stack
import scala.util.control.Breaks._
var brackets = Stack[Char]()
try {
for (c <- s) {
println(c)
c match {
case '(' | '{' | '[' => brackets.push(c)
case ')' => var c1 = brackets.pop; if (c1 != '(') {
break
}
case '}' => var c1 = brackets.pop; if (c1 != '{') {
break
}
case ']' => var c1 = brackets.pop; if (c1 != '[') {
break
}
}
}
if (brackets.size == 0) true else false
} catch {
case ex: Exception => println("Exception"); ex.printStackTrace(); false
}
}
}
But the interviewer asked to to use the immutable stack instead of mutable as mutable is not thread-safe and it won't work as expected in multi threaded environment.
I am not sure how to implement the same algorithm in scala using immutable stack. Can anyone help me with the same.