Leetcode题解14 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 class Solution {
     public static boolean isValid(String s) {
        Stack<Character> mStack = new Stack<Character>();
        for (int i = 0; i < s.length(); i++) {
            switch (s.charAt(i)) {
                case '{':
                case '[':
                case '(':
                    mStack.push(s.charAt(i));
                    break;
                case '}':
                    if (mStack.isEmpty())
                        return false;
                    if ('{' != mStack.pop())
                        return false;
                    break;
                case ']':
                    if (mStack.isEmpty())
                        return false;
                    if ('[' != mStack.pop())
                        return false;
                    break;
                case ')':
                    if (mStack.isEmpty())
                        return false;
                    if ('(' != mStack.pop())
                        return false;
                default:
            }
        }
        if (mStack.isEmpty())
            return true;
        else
            return false;
    }
}

你可能感兴趣的:(LeetCode)