Can somebody explain to me the algorithm for the Parenthesis Balancing problem?
"Is the string (code) syntax correct on account of matching parentheses couples?"
I can't figure it out apart from the fact that for each " ( " there should be another " ) " for the algorithm to return true.
Thanks!
I found this solution but I do not understand it and I don't want to copy and paste it:
def balance(chars: List[Char]): Boolean = {
def balanced(chars: List[Char], open: Int): Boolean = {
if (chars.isEmpty) open == 0
else
if (chars.head == '(') balanced(chars.tail,open+1)
else
if (chars.head == ')') open>0 && balanced(chars.tail,open-1)
else balanced(chars.tail,open)
}
balanced(chars,0)
}