算法test010
判断一个运算表达式的左右括号是否全部合法
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();
}}
欢迎交流指正~
算法 文章被收录于专栏
根据自己所见所闻进行算法归纳总结
腾讯成长空间 5879人发布