> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/algorithm-practice/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/algorithm-practice/leetcode/stack/20-valid-parentheses.md).

# 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)
