LeetCode 20-有效括号

1.有效括号

//例:( )     ( ( )     时间复杂度:O(n)
public class IsValid20 {
    // 存储括号的数据结构HashMap
    private HashMap<Character, Character> mappings;
    // 构造方法  初始化数据
    public IsValid20() {
        this.mappings = new HashMap<Character, Character>();
        this.mappings.put(')', '(');
        this.mappings.put('}', '{');
        this.mappings.put(']', '[');
    }
    //判断括号是否有效
    public boolean isValid(String s) {
        // 使用数据结构Stack栈
        Stack<Character> stack = new Stack<Character>();
        //for循环遍历字符串
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            // 遍历的字符串是否包含在hashmap的key中
            if (this.mappings.containsKey(c)) {
                // 栈为空则返回# ; 栈不为空则弹出栈顶元素
                char topElement = stack.empty() ? '#' : stack.pop();
                // 弹出的栈顶元素如果不在hashmap的key中,则返回false
                if (topElement != this.mappings.get(c)) {
                    return false;
                }
            } else {
                // 如果是不包含在hashmap的key中的括号,则压入栈中
                stack.push(c);
            }
        }
        // 没有括号
        return stack.isEmpty();
    }
}

2. 动画描述

动画描述

 

 

3.leetCode测试结果

发布了53 篇原创文章 · 获赞 0 · 访问量 1651

猜你喜欢

转载自blog.csdn.net/weixin_45450428/article/details/103906120