zoukankan      html  css  js  c++  java
  • 算法练习题---有效的括号

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

    有效字符串需满足:

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

    示例 1:

    输入: "()"
    输出: true
    示例 2:

    输入: "()[]{}"
    输出: true
    示例 3:

    输入: "(]"
    输出: false
    示例 4:

    输入: "([)]"
    输出: false
    示例 5:

    输入: "{[]}"
    输出: true

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/valid-parentheses

    解答:
    package com.zx.leetcode.validparenthesis;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Queue;
    import java.util.Stack;
    import java.util.concurrent.ConcurrentLinkedQueue;
    
    /**
     * @Author JAY
     * @Date 2019/7/7 16:12
     * @Description 有效的括号
     **/
    public class Solution {
    
        public static void main(String[] args) {
            String str = "()[ ] { }";
            System.out.println(isValid(str));
        }
    
    
        public static boolean isValid(String str) {
    
            if (str == null || str.length() == 0){
                return true;
            }
    
            Stack<String> stack = new Stack<>();
    
            for (int i = 0; i< str.length(); i++){
                String element = str.substring(i, i + 1).trim();
                if (!"".equals(element)){
                    if (stack.empty()){
                        stack.push(element);
                    } else {
                        //取出栈顶元素进行匹配
                        //查看栈中首个元素,并不移除
                        String peek = stack.peek();
                        //判断新元素是否与栈顶元素匹配对应
                        if (validMatch(element,peek)){
                            //如果匹配,移除栈顶元素
                            stack.pop();
                        }else {
                            //如果不匹配,继续将新元素压入栈顶
                            stack.push(element);
                        }
                    }
                }
            }
            //最后校验栈中是否还有元素,有,说明没有完全匹配,则返回false
            if (!stack.empty()){
                return false;
            }
    
            return true;
        }
    
        private static boolean validMatch(String element, String peek) {
    
            if (("(".equals(peek) && ")".equals(element))
                    || ("{".equals(peek) && "}".equals(element))
                    || ("[".equals(peek) && "]".equals(element))){
                return true;
            }
    
            return false;
    
        }
    
    }






  • 相关阅读:
    Ocaml入门(3)
    Delphi数组成员丢失
    Delphi合并2个动态数组
    Delphi用指针读取数组某个元素
    Delphi函数返回数组之TList函数返回
    Delphi函数返回数组之使用TList参数
    Delphi让函数返回数组
    Delphi双向链表
    Delphi指针与string
    Delphi函数指针,用于加载DLL
  • 原文地址:https://www.cnblogs.com/ningJJ/p/11146770.html
Copyright © 2011-2022 走看看