[LeetCode] 20. Valid Parentheses(有效的括号)
-
Difficulty: Easy
-
Related Topics: String, Stack
Description
Given a string s
containing just the characters (
, )
, {
, }
, [
and ]
, determine if the input string is valid.
给一个包含三种括号((){}[]
)的字符串 s
,判断其是否是有效的。
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.
左括号必须按正确的顺序被关闭
Examples
Example 1
Input: s = "()"
Output: true
Example 2
Input: s = "()[]{}"
Output: true
Example 3
Input: s = "(]"
Output: false
Example 4
Input: s = "([)]"
Output: false
Example 5
Input: s = "{[]}"
Output: true
Constraints
-
1 <= s.length <= 10^4
-
s
consists of parentheses only'()[]{}'
.
Hints
-
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g.
一个有关合法括号表达式的一个有趣的属性是:一个合法的括号表达式,其子表达式也会是一个合法的表达式(当然,不是所有的子表达式都符合),例如:
{ { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression
Can we exploit this structure somehow?
能否利用这种结构?
-
What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g.
当无论什么时候,只要在表达式内找到一对合法的括号,我们就移除它们,会发生什么呢?这有利于简化表达式,例如:
{ { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION!
-
The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help up process this recursively i.e. from outside to inwards.
栈这个数据结构可以很容易地描述问题中的结构。当总体结构无法把握时,处理过程无法从里向外进行。但,栈可以帮助我们从外向里地解决它。
Solution
利用栈这个数据结构,从题目的描述中可以发现,合法的括号对具有栈的性质:左括号是入栈操作,右括号是出栈操作。出入栈的顺序一致即合法,代码如下:
import java.util.*
class Solution {
fun isValid(s: String): Boolean {
val stack = ArrayDeque<Char>()
for (c in s) {
when (c) {
'(', '{', '[' -> stack.push(c)
')', '}', ']' -> if (!matches(c, stack)) return false
else -> return false
}
}
return stack.isEmpty()
}
private fun matches(c: Char, stack: Deque<Char>): Boolean {
if (stack.isEmpty()) {
return false
}
val map = mapOf(
'(' to ')', '[' to ']', '{' to '}'
)
return map[stack.pop()]?:'\u0000' == c
}
}