leetcode刷题笔记20

こ雲淡風輕ζ 提交于 2020-02-07 05:13:22

有效的括号

利用栈先进后出的特性实现

class Solution {

    private HashMap<Character,Character> map;
    public Solution(){
        this.map = new HashMap<>();
        map.put('(',')');
        map.put('{','}');
        map.put('[',']');
    }
    public boolean isValid(String s) {
        Stack<Character> st = new Stack<>();
        for(int i = 0; i < s.length(); i++){
            char c = s.charAt(i);
            if(map.containsKey(c)){
                st.push(c);
            }else{
                if(st.empty()) return false;
                char topelement = st.pop();
                if(map.get(topelement) != c) return false;
            }
        }
        return st.empty()? true : false;
    }
}

运行结果:
在这里插入图片描述
题目来源leetcode 题库20题

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!