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();
        }
    }

     下图较简洁:

  • 相关阅读:
    CSS——制作天天生鲜主页
    HTML——制作一个图片列表
    HTML——制作一个简易菜单栏
    CSS——三种页面引入方法
    【20170903】模拟赛
    【LA 3942】 Remember the word
    【BZOJ 1036】 树的统计count
    UVA 12299 RMQ with shifts
    【20170706】次短路
    【20170706】保卫萝卜
  • 原文地址:https://www.cnblogs.com/stono/p/9475505.html
Copyright © 2011-2022 走看看