Valid Parentheses

Given a string containing just the characters

’(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’

determine if the input string is valid.

The brackets must close in the correct order,

”()” and “()[]{}”

are all valid but

”(]” and “([)]”

are not.

val brackets:Map[Char, Char] = Map[Char, Char] (
  ')' -> '(',
  '}' -> '{',
  ']' -> '['
)

def isValid(s: String): Boolean = {
  var lst: List[Char] = Nil
  for (c <- s) {
    if (brackets contains c) {
      for (open <- brackets.get(c)) {
        if (lst.head == open) lst = lst.tail
        else return false
      }
    } else {
      lst = c :: lst
    }
  }
  lst.isEmpty
}

isValid("()")
isValid("()[]{}")
isValid("(]")
isValid("([)]")