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.
判断括号的合法性。用栈就可以搞定。
一开始用了一个HashMap用来做右括号对左括号的映射,后来看到网友有更好的表达方式,就采用了。程序如下所示:
class Solution {
public boolean isValid(String s) {
ArrayDeque<Character> stack = new ArrayDeque<>();
int len = s.length();
// Map<Character, Character> map = new HashMap<>();
// map.put(')', '(');
// map.put(']', '[');
// map.put('}', '{');
char ch;
for (int i = 0; i < len; ++ i){
ch = s.charAt(i);
if (ch == '('){
stack.push(')');
}
else if (ch == '['){
stack.push(']');
}
else if (ch == '{'){
stack.push('}');
}
else {
if (stack.isEmpty()||stack.pop() != ch){
return false;
}
}
}
return stack.isEmpty();
}
}