题目
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
思路
想象一下,你正在为你的大学课设编写一个小型编译器,编译器的任务之一(或称子任务)将检测括号是否匹配。
我们本文中看到的算法可用于处理编译器正在编译的程序中的所有括号,并检查是否所有括号都已配对。这将检查给定的括号字符串是否有效,是一个重要的编程问题。
使用栈作为该问题的中间数据结构的算法。利用栈先进后出的本质和括号的匹配本质,把左括号放入栈中。
算法
初始化栈 S。一次处理表达式的每个括号。如果遇到开括号,我们只需将其推到栈上即可。这意味着我们将稍后处理它,让我们简单地转到前面的 子表达式(判断两个括号是否匹配)。如果我们遇到一个闭括号,那么我们检查栈顶的元素。如果栈顶的元素是一个 相同类型的 左括号,那么我们将它从栈中弹出并继续处理。否则,这意味着表达式无效。如果到最后我们剩下的栈中仍然有元素,那么这意味着表达式无效。
Python解法
class Solution(object):
def isValid(self
, s
):
"""
:type s: str
:rtype: bool
"""
stack
= []
paren_map
= {')':'(',']':'[','}':'{'}
for c
in s
:
if c
not in paren_map
:
stack
.append
(c
)
elif not stack
or paren_map
[c
] != stack
.pop
():
return False
return not stack
class Solution(object):
def isValid(self
, s
):
"""
:type s: str
:rtype: bool
"""
stack
= []
mapping
= {")": "(", "}": "{", "]": "["}
for char
in s
:
if char
in mapping
:
top_element
= stack
.pop
() if stack
else '#'
if mapping
[char
] != top_element
:
return False
else:
stack
.append
(char
)
return not stack
Java解法
class Solution {
private HashMap
<Character, Character> mappings
;
public Solution() {
this.mappings
= new HashMap<Character, Character>();
this.mappings
.put(')', '(');
this.mappings
.put('}', '{');
this.mappings
.put(']', '[');
}
public boolean isValid(String s
) {
Stack
<Character> stack
= new Stack<Character>();
for (int i
= 0; i
< s
.length(); i
++) {
char c
= s
.charAt(i
);
if (this.mappings
.containsKey(c
)) {
char topElement
= stack
.empty() ? '#' : stack
.pop();
if (topElement
!= this.mappings
.get(c
)) {
return false;
}
} else {
stack
.push(c
);
}
}
return stack
.isEmpty();
}
}