20. Valid Parentheses

  1. 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.

方法:Stack 左括号时入栈相关info,右括号时使出栈检查配对

思路:
遇到'(', '[', '{' 时将所需配对的右括号 入栈,其他字符时与出栈字符看是否相等(验证是否因为上一个未匹配的左括号所需)
Time Complexity: O(n)
Space Complexity: O(n)

Solution Code:

public class Solution {
    public boolean isValid(String s) {
        Deque stack = new ArrayDeque();
        for(int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if(c == '(') stack.push(')');
            else if(c == '[') stack.push(']');
            else if(c == '{') stack.push('}');
            else if (stack.isEmpty() || stack.pop() != c)
                return false;
        }
        return stack.isEmpty();
    }
}

你可能感兴趣的:(20. Valid Parentheses)