zoukankan      html  css  js  c++  java
  • 20. Valid Parentheses

    Given a string 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.

    Note that an empty string is also considered valid.

    Example 1:

    Input: "()"
    Output: true
    

    Example 2:

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

    Example 3:

    Input: "(]"
    Output: false
    

    Example 4:

    Input: "([)]"
    Output: false
    

    Example 5:

    Input: "{[]}"
    Output: true
    
    //Time: O(n), Space: O(n)   
     public boolean isValid(String s) {
            if (s == null || s.length() == 0) {
                return true;
            }
            
            Stack<Character> stack = new Stack<Character>();
            
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                
                if (c == '(') {
                    stack.push(')');
                } else if (c == '[') {
                    stack.push(']');
                } else if (c == '{') {
                    stack.push('}');
                } else {
                    if (stack.isEmpty() || stack.pop() != c) {
                        return false;
                    }
                }
            }
            
            return stack.isEmpty();//注意[的情况
        }
  • 相关阅读:
    python 获取Excel 的内容
    python 获取文件Excel 的行数与列数
    python 读取Excel 取出表头(列名)
    DRF的视图组件
    Redis
    Git的故事
    DRF的JWT用户认证
    DRF的三大认证组件
    DRF的序列化组件
    DRF的请求响应组件
  • 原文地址:https://www.cnblogs.com/jessie2009/p/9810121.html
Copyright © 2011-2022 走看看