20. 有效的括号,多种解法(经典的栈的应用)(Java实现)

78 篇文章 0 订阅
这篇博客探讨了三种不同的括号匹配算法实现,包括原始、冗余和优化的方法。第一种是基础的栈操作,第二种引入了冗余的字符串转换,而第三种使用HashMap提升了效率。每种方法都详细解释了其工作原理,并分析了它们的效率和可读性。
摘要由CSDN通过智能技术生成

在这里插入图片描述

class Solution {
    public boolean isValid(String s) {
        int len = s.length();
        if (len == 0) return true;
        Stack<Character> stack = new Stack();
        char temp;
        for (int i = 0; i < len; i++){
            temp = s.charAt(i);
            if (temp == '{' || temp == '[' || temp == '('){
                stack.push(temp);
            }else{ //右括号
                if (stack.isEmpty()) return false;
                
                char left = stack.pop();
                if (left == '(' && temp != ')') return false;
                if (left == '{' && temp != '}') return false;
                if (left == '[' && temp != ']') return false;
                
            }
        }
        return stack.isEmpty();

    }
}

再附上第一次写的冗余代码

class Solution {
    public boolean isValid(String s) {
        int len = s.length();
        if (len == 0) return true;
        if (s.charAt(0) == ')' || s.charAt(0) == ']'||s.charAt(0) == '}'  ) return false;
        Stack<String> stack = new Stack();
        String temp;
        for (int i = 0; i < len; i++){
            temp = s.charAt(i)+"";
            switch(temp){
                case "(": stack.push("("); break;
                case "[": stack.push("["); break;
                case "{": stack.push("{"); break;
                case ")":{
                    if (stack.empty()) return false;
                    else if (!stack.pop().equals("(")) return false; break;
                }
                case "]":{
                    if (stack.empty()) return false;
                    else if (!stack.pop().equals("[")) return false; break;
                }
                case "}":{
                    if (stack.empty()) return false;
                    else if (!stack.pop().equals("{")) return false; break;
                }
            }
        }
        return stack.empty();
    }
}

最容易理解的算法(但是效率较低)

class Solution {
    public boolean isValid(String s) {
        while (s.contains("{}") || s.contains("()") || s.contains("[]")){
            s = s.replace("{}", "");
            s = s.replace("()", "");
            s = s.replace("[]", "");
        }

        return s.isEmpty();
    }
}

使用HashMap优化第一个解法

class Solution {
	private static HashMap<Character,Character> map = new HashMap<>();
    static {
        map.put('(',')');
        map.put('[',']');
        map.put('{','}');
    }
    public boolean isValid(String s) {
        if (s.length() == 0) return true;
        int len = s.length();
        Stack<Character> stack = new Stack();
        char temp;
        for (int i = 0; i < len; i++){
            temp = s.charAt(i);
            if (map.containsKey(temp)){
                stack.push(temp);
            }else{ //右括号
                if (stack.isEmpty()) return false;
                
                char left = stack.pop();
                if (map.get(left) != temp) return false;//栈顶元素与这个元素不匹配

            }
        }
        return stack.isEmpty();

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值