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 有什么问题可以给我留言噢~
  • 相关阅读:
    ixgbe dma 控制器
    per cpu
    HDU 4597 Play Game
    HDU 5115 Dire Wolf
    hdu 5900 QSC and Master
    CodeForces933A A Twisty Movement
    CodeForces 245H Queries for Number of Palindromes
    CodeForces596D Wilbur and Trees
    CodeForces509F Progress Monitoring
    CodeForces149D Coloring Brackets
  • 原文地址:https://www.cnblogs.com/flyingcr/p/10326894.html
Copyright © 2011-2022 走看看