leetcode刷题笔记二十 有效的括号 Scala版本
leetcode刷题笔记二十 有效的括号 Scala版本
源地址:20. 有效的括号
问题描述:
Given a string containing just the characters
'('
,')'
,'{'
,'}'
,'['
and']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
代码补充:
//本题是一个典型的栈的应用,遇到左侧括号则入栈,遇到右侧括号有两种可能性,栈空或者出栈的括号与右侧入栈括号未能对应返回false
import scala.collection.mutable.Stack
object Solution {
def isValid(s: String): Boolean = {
if ( s == "") return true
val stack = Stack[Char]()
for (elem <- s){
elem match {
case '(' => stack.push(elem)
case '[' => stack.push(elem)
case '{' => stack.push(elem)
case ')' => if (stack.length == 0 || stack.pop != '(') return false
case ']' => if (stack.length == 0 || stack.pop != '[') return false
case '}' => if (stack.length == 0 || stack.pop != '{' ) return false
case _ => return false
}
}
//如果左侧括号入栈仍有剩余未匹配,则false
if (stack.length == 0) return true
else return false
}
}