# 20 Valid Parentheses

## 20. [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/description/)

## 1. Question

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.

## 2. Implementation

思路：查看括号匹配问题，就看相应的符号是否对称，可以直接用stack做

```java
class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();

        for (char c : s.toCharArray()) {
            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();
    }
}
```

## 3. Time & Space Complexity

时间和空间都是O(n)
