zoukankan      html  css  js  c++  java
  • 20. Valid Parentheses检验括号字符串的有效性

    Given a string s containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

    An input string is valid if:

    1. Open brackets must be closed by the same type of brackets.
    2. Open brackets must be closed in the correct order.

     

    Example 1:

    Input: s = "()"
    Output: true
    

    Example 2:

    Input: s = "()[]{}"
    Output: true
    

    Example 3:

    Input: s = "(]"
    Output: false
    

    Example 4:

    Input: s = "([)]"
    Output: false
    

    Example 5:

    Input: s = "{[]}"
    Output: true

    这种带技巧的题,真的忘了

    思路是:先全部push进去,再pop

    
    

    stack.pop() == null会出异常,所以应该是stack.isEmpty()

    
    

    最后检查一下stack是否为空

    class Solution {
        public boolean isValid(String s) {
            //cc
            if (s == null || s == "")
                return true;
            
            //新建一个stack,遍历s中的每一个元素
            Stack<Character> stack = new Stack<Character>();
            
            //返回
            for (char c : s.toCharArray()) {
                if (c == '(') {
                    stack.push(')');
                } else if (c == '{') {
                    stack.push('}');
                } else if (c == '[') {
                    stack.push(']');
                } else {
                    if (stack.pop() == null || stack.pop() != c)
                        return false;
                }
            }
            
            return stack.isEmpty();
        }
    }
    View Code
     
  • 相关阅读:
    input 正则
    .net ashx Session 未将对象引用到实例
    js 时间和时间对比
    c# Repeater 和 AspNetPager
    c#后台 极光推送到Android 和IOS客户端
    select scope_identity()
    redhat7.4安装git(按照官网从源码安装)
    redhat7.4安装gitlab
    ES6模板字符串
    初次接触webpack
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13871778.html
Copyright © 2011-2022 走看看