public boolean isValid (String s) {
// write code here
if(s==null) return true;
char[] c=s.toCharArray();
Stack<Character> stack=new Stack();
Map<Character,Character> map=new HashMap<>();
map.put(')','(');
map.put('}','{');
map.put(']','[');
for(char cc:c){
if(cc=='(' || cc=='{' || cc=='['){
stack.push(cc);
//主要就是注意在栈空的时候 也是不合法的;并且在执行栈方法的时候也需要去判断栈是否为空
}else if(stack.isEmpty()||stack.pop()!=map.get(cc)){
return false;
}
}
//最后栈里面可能还有括号序列此时也是不合法的
return stack.isEmpty()?true:false;
}
京公网安备 11010502036488号