核心思路:Stack+Map
技巧:Map中把Key值设为右括号,把左括号设置为Value。
遍历完字符串,如果栈内依然为空,则证明该字符串合格。
class Solution {
public boolean isValid(String s) {
int len = s.length();
if(len%2 == 1){
return false;
}
HashMap<Character,Character> hashmap = new HashMap<>();
hashmap.put(')','(');
hashmap.put(']','[');
hashmap.put('}','{');
Stack<Character> stack = new Stack<>();
for(int i = 0; i < len; i++){
char c = s.charAt(i);
if(hashmap.containsKey(c) && !stack.empty()){
char cc = stack.pop();
if(cc != hashmap.get(c)){
return false;
}
}else{
stack.push(c);
}
}
return stack.empty();
}
}