算法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();
}

}
欢迎交流指正~

算法 文章被收录于专栏

根据自己所见所闻进行算法归纳总结

全部评论

相关推荐

06-17 21:57
门头沟学院 Java
白友:噗嗤,我发现有些人事就爱发这些,明明已读不回就行了,就是要恶心人
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务