stack实现括号匹配

stack实现括号匹配

1.通过String类的内置函数置空string

public static boolean isValidByIf(String s){
while (s.contains("{}")||s.contains("[]")||s.contains("()")){
s=s.replace("{}","");
s=s.replace("[]","");
s=s.replace("()","");

    }
    return s.isEmpty();
}

2.通过stack实现

public static boolean isValidByStack(String s) {
       Stack<Character> stack = new Stack<>();
       char[] ch = s.toCharArray();
       for (int i = 0; i < ch.length; i++) {//遍历字符数组,是左括号入栈
           if (ch[i] == '(' || ch[i] == '[' || ch[i] == '{') {
               stack.push(ch[i]);
           } else {
//                右括号
               if (stack.isEmpty()) return false;//stack为空不存在左括号,只有右括号所有无效
//                弹出栈顶元素
               Character left = stack.pop();
               if (left == '(' && ch[i] != ')') return false;
               if (left == '{' && ch[i] != '}') return false;
               if (left == '[' && ch[i] != ']') return false;
           }
       }
//        stack为空,则括号匹配,有效,否则不为空,无效
       return stack.isEmpty();
   }

3.通过hashmap键值对的形式实现

 public static boolean isValidByHM(String s) {
        Stack<Character> stack = new Stack<>();
        char[] ch = s.toCharArray();
        for (int i = 0; i < ch.length; i++) {//遍历字符数组,是左括号入栈
            if (hashMap.containsKey(ch[i])) {
                stack.push(ch[i]);
            } else {
//                右括号
                if (stack.isEmpty()) return false;//stack为空不存在左括号,只有右括号所有无效
//                弹出栈顶元素
                Character left = stack.pop();
//                hashMap.get(left)根据栈弹出的left左括号get取值为对应的右括号,而ch[i]为右括号,不等则false
                if (ch[i]!=hashMap.get(left)) return false;
            }
        }
//        stack为空,则括号匹配,有效,否则不为空,无效
        return stack.isEmpty();
    }
posted @   MGLblog  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示