前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode刷题(30)——20. 有效的括号

leetcode刷题(30)——20. 有效的括号

作者头像
老马的编程之旅
发布2022-06-22 13:30:31
1780
发布2022-06-22 13:30:31
举报
文章被收录于专栏:深入理解Android

给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。

示例 1: 输入: “()” 输出: true

示例 2: 输入: “()[]{}” 输出: true

示例 3: 输入: “(]” 输出: false

示例 4: 输入: “([)]” 输出: false

示例 5: 输入: “{[]}” 输出: true

这里不能简单统计括号出现的次数是否匹配,如下面的写法就是错误的:

代码语言:javascript
复制
class Solution {
    public boolean isValid(String s) {
        int left1=0;
        int left2=0;
        int left3=0;
        int right1=0;
        int right2=0;
        int right3=0;
        for(int i=0;i<s.length();i++){
            char c = s.charAt(i);
            if(c=='['){
                left1++;
            }else if(c==']'){
                right1++;
            }else if(c=='('){
                left2++;
            }else if(c==')'){
                right2++;
            }else if(c=='{'){
                left3++;
            }else if(c=='}'){
                right3++;
            } 
        }
        return left1==right1&&left2==right2&&left3==right3;

    }
}

算法 1.初始化栈 S。 2.一次处理表达式的每个括号。 3.如果遇到开括号,我们只需将其推到栈上即可。这意味着我们将稍后处理它,让我们简单地转到前面的 子表达式。 4.如果我们遇到一个闭括号,那么我们检查栈顶的元素。如果栈顶的元素是一个 相同类型的 左括号,5.那么我们将它从栈中弹出并继续处理。否则,这意味着表达式无效。 如果到最后我们剩下的栈中仍然有元素,那么这意味着表达式无效。

代码语言:javascript
复制
private HashMap<Character, Character> mappings;

        // Initialize hash map with mappings. This simply makes the code easier to read.
        public Solution() {
            this.mappings = new HashMap<Character, Character>();
            this.mappings.put(')', '(');
            this.mappings.put('}', '{');
            this.mappings.put(']', '[');
        }

        public boolean isValid(String s) {

            // Initialize a stack to be used in the algorithm.
            Stack<Character> stack = new Stack<Character>();

            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);

                // If the current character is a closing bracket.
                if (this.mappings.containsKey(c)) {

                    // Get the top element of the stack. If the stack is empty, set a dummy value of '#'
                    char topElement = stack.empty() ? '#' : stack.pop();

                    // If the mapping for this bracket doesn't match the stack's top element, return false.
                    if (topElement != this.mappings.get(c)) {
                        return false;
                    }
                } else {
                    // If it was an opening bracket, push to the stack.
                    stack.push(c);
                }
            }

            // If the stack still contains elements, then it is an invalid expression.
            return stack.isEmpty();
        }

注意: 1.这里使用的是Character,所以this.mappings.put(’}’, ‘{’);需要使用单引号,topElement != this.mappings.get©使用的是不等于,而不是equals,因为char是没有equals方法的 2.最后需要返回stack.isEmpty(),如果都匹配了,stack会是空的

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-11-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档