# 20. Valid Parentheses



![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-Mdz2EqRcCzQoAKwzN9J%2F-Mdz2gS40EkR0y2wiArv%2Fimage.png?alt=media\&token=5d4ee409-2da8-41a5-8f17-ed0d02f61953)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-Mdz2EqRcCzQoAKwzN9J%2F-Mdz2juU4ZOX11pxLTNT%2Fimage.png?alt=media\&token=1b2fcb3c-0060-4623-b50c-08df59b59af6)

## brute force

ex:  if have '(',   replace  ')' , one by one...

## use stack

```java
/*
    time: O(n)
    space: O(n)
*/
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) {
                stack.push(')');
                
            } else if ('[' == c) {
                stack.push(']');
                
            } else if ('{' == c) {
                stack.push('}');
                
            } else if (stack.isEmpty() || stack.pop() != c) {
                return false;    
            }
        }
        
        return stack.isEmpty(); // notice here!
    }
}
```



or

```java
class Solution {
    public boolean isValid(String s) {
        // if "(" push ")", or ")" pop, finally statck is empty => true
        Stack<Character> stack = new Stack<>();
        for (Character c : s.toCharArray()) {
            if (c == '(' || c == '[' || c == '{') {
                stack.push(c);
            } else {
                if (stack.isEmpty()) return false;
                
                Character top = stack.pop();
                if (!(top == '(' && c == ')' || 
                     top == '[' && c == ']' ||
                     top == '{' && c == '}')) {
                    return false;
                }
            } 
        }
        return stack.isEmpty();
    }
}
```
