zoukankan      html  css  js  c++  java
  • 20. 有效的括号

    20. 有效的括号

    题目:https://leetcode-cn.com/problems/valid-parentheses/description/

    package com.test;
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Stack;
    
    public class Lesson020 {
        public static void main(String[] args) {
            String input = "{()[]}";
            boolean res = isValid(input);
            System.out.println(res);
        }
    
        private static boolean isValid(String s) {
            Stack<String> stack = new Stack<>();
            // 定义左右括号字符串
            String right = ")}]";
            String left = "({[";
            // 定义左右括号对应关系
            Map<String, String> map = new HashMap<>();
            map.put("(", ")");
            map.put("{", "}");
            map.put("[", "]");
            if("".equals(s)){
                return true;
            }
            for (int i = 0; i < s.length(); i++) {
                String substring = s.substring(i, i + 1);
                // 如果是左括号就放到堆栈中
                if (left.indexOf(substring) > -1) {
                    stack.push(substring);
                }
                // 如果是右括号就与堆栈中的字符串进行对比
                if (right.indexOf(substring) > -1) {
                    // 堆栈里面没有内容了就返回false
                    if (stack.empty()) {
                        return false;
                    }
                    String pop = stack.pop();
                    // 字符串不一致就返回false
                    if(!substring.equals(map.get(pop))){
                        return false;
                    }
                }
            }
            // 全部循环完毕,堆栈里面还有内容就是false
            return stack.empty();
        }
    }

     下图较简洁:

  • 相关阅读:
    mongodb教程
    redis高级知识
    memcached删除机制与大数据缓存问题
    nginx 运维基础
    mysql 集群与分区
    Memcached之缓存雪崩,缓存穿透,缓存预热,缓存算法
    git cz配置
    Angular零碎知识点-持续补充
    Vue学习笔记-组件
    Vue学习笔记-自定义指令生命周期函数
  • 原文地址:https://www.cnblogs.com/stono/p/9475505.html
Copyright © 2011-2022 走看看