就是栈。用map存储括号类型,遇到右括号弹栈,不匹配为false。左括号压栈。
class Solution {
HashMap<Character,Character> chars;
public Solution(){
this.chars = new HashMap<Character,Character>();
this.chars.put(\')\',\'(\');
this.chars.put(\']\',\'[\');
this.chars.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.chars.containsKey(c)){
char topElement = stack.empty()?\'#\':stack.pop();
if(topElement != this.chars.get(c)){
return false;
}
}else{
stack.push(c);
}
}
return stack.isEmpty();
}
}