判断一个运算表达式的左右括号是否全部合法
public class test010 {
private HashMap<Character, Character> mappings;
public test010() {
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 { if(c=='('||c=='['||c=='{'){ stack.push(c); } } } return stack.isEmpty(); }
}
欢迎交流指正~