zoukankan      html  css  js  c++  java
  • Leetcod--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


    正常的代码
    class Solution {
        public boolean isValid(String s) {
            Stack<Character> st=new Stack<Character>();
            for(char c:s.toCharArray()){
                if(c=='('||c=='['||c=='{')
                    st.push(c);
                else if(c=='}'&&!st.empty()&&st.peek()=='{')
                    st.pop();
                else if(c==']'&&!st.empty()&&st.peek()=='[')
                    st.pop();
                else if(c==')'&&!st.empty()&&st.peek()=='(')
                    st.pop();
                else 
                    return false;
            }
            return st.empty();
        }
    }

    很巧妙的方法
    class Solution {
        public boolean isValid(String s) {
            Stack<Character> st=new Stack<Character>();
            for(char c:s.toCharArray()){
                if(c=='(')
                    st.push(')');
                else if(c=='[')
                    st.push(']');
                else if(c=='{')
                    st.push('}');
                else if(st.empty()||st.pop()!=c)
                    return false;
            }
            if(st.empty())
                return true;
            else
                return false;
        }
    }
  • 相关阅读:
    转发和重定向的区别
    关于Daydream VR的最直白的介绍
    Duplicate Protocol Definition of DTService Is Ignored
    automatically select architectures
    java
    初识反射
    java网络编程
    Map接口
    Set,List
    正则表达式
  • 原文地址:https://www.cnblogs.com/albert67/p/10360234.html
Copyright © 2011-2022 走看看