# Leetcode 20 Valid Parentheses
###### tags: `Leetcode` `程式菜雞的coding日常`
## 題目原文
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.
Every close bracket has a corresponding open bracket of the same type.
Example 1:
> Input: s = "()"
Output: true
Example 2:
> Input: s = "()[]{}"
Output: true
Example 3:
> Input: s = "(]"
Output: false
## 題目理解
經典(?)的檢查括號有沒有錯的問題,就這樣(?)
## 解題思路
用stack,如果為空,讀到什麼東西就丟進去
如果讀到右括號,則判斷當前stack的top是否可以與其配對,如果可以則pop,不行則一樣丟進stack裡,方便後續判斷。
全部讀完之後,如果全部括號都可以正確的配對,則stack會為空,因此讀完之後判斷stack是否為空即可。
## 程式實作
```cpp=
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(char ch:s){
if(st.empty())
st.push(ch);
else if(st.top() == '(' && ch == ')')
st.pop();
else if(st.top() == '{' && ch == '}')
st.pop();
else if(st.top() == '[' && ch == ']')
st.pop();
else
st.push(ch);
}
if(st.empty())
return true;
return false;
}
};
```
## 後記 ~~(幹話)~~
2023/4/10的daily challenge
今天的好簡單啊(?)
現在覺得leetcode的好處在於不用處理I/O,測資也不會特別搞你,不像我程式設計課的作業,題目說輸入數字然後助教就塞一個英文字進去,做防呆的時間花的比做程式本體還多。