括号对称匹配算法
class Solution {
private HashMap<Character,Character> mappings;
public Solution() {
//构建一个存放对应括号的map
this.mappings = new HashMap<Character,Character>();
this.mappings.put(')','(');
this.mappings.put('}','{');
this.mappings.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.mappings.containsKey(c)) {
char topElement = stack.empty() ?'#':stack.pop();
if(topElement != this.mappings.get(c)) {
return false;
}
}else {
stack.push(c);
}
}
return stack.isEmpty();
}
}