---
# System prepended metadata

title: Question 20. Valid Parentheses
tags: [leetcode]

---

###### tags: `leetcode`
# Question 20. Valid Parentheses
### Description:
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
### Solution:
Stack
```
- include <stack>
- initial
    - stack<char> mystack, mystack2;
- mystack.size()
- mystack.empty()
- mystack.push(element)
- mystack.top()
- mystack.pop()
- mystack.swap(mystack2)
```
### AC code
```cpp=
#include <stack>

class Solution {
public:
    bool isValid(string s) {
        stack<char> stack;
        for(int i = 0 ; i < s.length() ; i++){
            if(s[i] == ')'){
                if(!stack.empty() && stack.top() == '(')
                    stack.pop();
                else{
                    return false;
                }
            }
            else if(s[i] == ']'){
                if(!stack.empty() && stack.top() == '[')
                    stack.pop();
                else{
                    return false;
                }
            }
            else if(s[i] == '}'){
                if(!stack.empty() && stack.top() == '{')
                    stack.pop();
                else{
                    return false;
                }
    
            else
                stack.push(s[i]);            
        }
        if(!stack.empty())
            return false;
        else
            return true;
    }
};
```