LeetCode 20 Valid Parentheses 括号匹配问题

题目:

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

翻译:

给一个字符串,判断括号是否匹配成功。


思路:

用一个字符栈,读到一个字符时判断,如果栈顶和当前这个字符是满足左右括号匹配,则弹出,否则压栈。

如果最后栈为空,说明匹配成功。 


代码:

 public static boolean isValid(String s) {
        if(s.length() == 0 )
            return true;
        Stack<Character> st = new Stack<Character>();
        st.push(s.charAt(0));
        for(int i = 1 ; i< s.length();i++)
        {
            if(!st.empty()&& ismatch(st.peek(), s.charAt(i)))//非空且栈顶和当前字符匹配,弹出
                st.pop();
            else {
                st.push(s.charAt(i));
            }
        }
        if(st.empty())
            return true;
        return false;
    }
    
    public  static  boolean ismatch(char a,char b)
    {
        if((a=='('&&b==')')||(a=='{'&&b=='}')||(a=='['&&b==']'))
            return true;
        else 
            return false;
    }


点赞