zoukankan      html  css  js  c++  java
  • Valid Parentheses

    1、题目

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
    An input string is valid if:
    Open brackets must be closed by the same type of brackets.
    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

    2、求解一

        public boolean isValid(String 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.isEmpty() || stack.pop() != c)
                    return false;
            }
            return stack.isEmpty();
        }
    该方法的亮点是利用了stack的后进先出的特点
    欢迎关注我的公众号:小秋的博客 CSDN博客:https://blog.csdn.net/xiaoqiu_cr github:https://github.com/crr121 联系邮箱:rongchen633@gmail.com 有什么问题可以给我留言噢~
  • 相关阅读:
    NOIP前的一些计划
    回文自动机[学习笔记]
    Luogu-3705 [SDOI2017]新生舞会
    01分数规划[学习笔记]
    jvm参数总结
    读懂jstack
    PRODUCER配置加载
    为什么WAIT必须在同步块中
    NIO学习笔记
    dp求最长递增子序列并输出
  • 原文地址:https://www.cnblogs.com/flyingcr/p/10326894.html
Copyright © 2011-2022 走看看