每次是左括号的话进栈,不是左括号的话出栈,看看遍历的当前字符与出栈的字符是否是匹配的
public boolean isValid3(String s) {
if (s.length() % 2 == 1) return false;
ArrayDeque stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c == ‘(’ || c == ‘{’ || c == ‘[’) {
stack.push( c ) ;
} else {
if (stack.isEmpty()) return false;
char top = stack.pop();
if (c == ‘)’ && top != ‘(’) return false;
if (c == ‘}’ && top != ‘{’) return false;
if (c == ‘]’ && top != ‘[’) return false;
}
}
return stack.isEmpty();
}