首页 > 其他 > 详细

Leetcod--20. Valid Parentheses(极简洁的括号匹配)

时间:2019-02-10 21:43:19      阅读:183      评论:0      收藏:0      [点我收藏+]

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;
    }
}

 

Leetcod--20. Valid Parentheses(极简洁的括号匹配)

原文:https://www.cnblogs.com/albert67/p/10360234.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!