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.

Tips:

用stack, 看到左括号就入栈,看到右括号就出栈看能不能匹配到左括号。

注意Stack里变量类型为character,不能用else if。

Code:

public class Solution {
    public boolean isValid(String s) {
        if (s == null || s.length() == 0) return true;
        Stack<Character> stack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (c == '(' || c == '{' || c == '[') stack.push(c);
            if (c == ')') if (stack.isEmpty() || stack.pop() != '(') return false;
            if (c == '}') if (stack.isEmpty() || stack.pop() != '{') return false;
            if (c == ']') if (stack.isEmpty() || stack.pop() != '[') return false;
        }
        return stack.isEmpty() ? true : false;
    }
}

results matching ""

    No results matching ""