Problem
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.
Note
简单来说,建立堆栈stack。先用哈希表存对应的parentheses pair,再遍历字符串s,用switch语句判断。如果是前括号,放入堆栈stack;如果是后括号,那么查看stack顶端的元素和当前元素是否在哈希表对应,若不对应或堆栈为空,就返回false,否则弹出栈顶元素并继续循环。
循环结束后,若未抛出false,且堆栈为空,说明所有parenthese都已一一对应。
Solution
public class Solution {
public boolean isValid(String s) {
Map<Character, Character> map = new HashMap<>();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
Character ch = s.charAt(i);
switch (ch) {
case '{': case '[': case '(':
stack.push(ch);
break;
case ')': case '}': case ']':
if (stack.isEmpty() || ch != map.get(stack.pop())) return false;
}
}
return stack.isEmpty();
}
}