I\'m working on some code to balance parenthesis, this question proved most useful for the algorithm.
I implemented it in my first language (PHP) but I\'m learning Scala
Instead of using Switch case you can use recursion to solve your problem in an efficient way.
Following is my code to achieve the same with the help of recursion. You need to convert the string to List for my method.
Code :
object Balance {
def main(args: Array[String]): Unit = {
var paranthesis = "(234(3(2)s)d)" // Use your string here
println(bal(paranthesis.toList)) // converting the string to List
}
def bal(chars: List[Char]): Boolean ={
// var check = 0
def fun(chars: List[Char],numOfOpenParan: Int): Boolean = {
if(chars.isEmpty){
numOfOpenParan == 0
}
else{
val h = chars.head
val n =
if(h == '(') numOfOpenParan + 1
else if (h == ')') numOfOpenParan - 1
else numOfOpenParan
// check = check + n
if (n >= 0) fun(chars.tail,n)
else false
}
}
fun(chars,0)
}
}