个人记录-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 class Solution {
    public boolean isValid(String s) {
        if (s == null || s.length() < 1) {
            return true;
        }

        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); ++i) {
            //'('、'['、'{'入栈;')'、']'、'}'出栈
            if (s.charAt(i) == '(' || s.charAt(i) == '['
                    || s.charAt(i) == '{') {
                stack.push(s.charAt(i));
            } else if (s.charAt(i) == ')') {
                //判断出栈条件是否满足
                if (!checkStack(stack, '(')) {
                    return false;
                }
            } else if (s.charAt(i) == ']') {
                if (!checkStack(stack, '[')) {
                    return false;
                }
            } else if (s.charAt(i) == '}') {
                if (!checkStack(stack, '{')) {
                    return false;
                }
            }
        }

        //成功匹配后,栈最后应该是空的
        return stack.empty();
    }

    private static boolean checkStack(Stack<Character> stack, char wanted) {
        //出栈时,必须匹配;例如碰到')', 那么栈顶必须是'('才行
        if (!stack.empty() && stack.peek() == wanted) {
            stack.pop();
            return true;
        }
        return false;
    }
}

你可能感兴趣的:(个人记录-LeetCode 20. Valid Parentheses)