# 解題紀錄 ## 題目:e924. pC. 括號配對 ## 📙 題目描述 請撰寫一個程式,輸入一行字串後,輸出該字串的括號配對是否正確。 要檢查的括號有圓括號 ()、方括號 []、小於大於括號 <> 和曲括號 {}。 ```txt 輸入第一行有一個正整數 T(1 ≤ T ≤ 1000), 代表接下來共有 T 行字串要驗證。 接下來依序有 T 行,每行為需要驗證括號配對的字串 s, 字串中只會出現 ()、[]、<> 和 {} ``` ```txt 輸出說明 若配對成功輸出 'Y' 若配對失敗輸出 'N' ``` ```txt 範例輸入 #1 4 {()<>}[] (){ {(}) ()) 範例輸出 #1 Y N N N ``` --- ## ✒️ 解題思路 這題需了解**堆疊stack** 遇到左括號就push到堆疊中 遇到右括號就從堆疊pop出匹配的括號 --- ## 💻 C++解法 ```cpp #include <bits/stdc++.h> using namespace std; class Solution { private: string s; public: Solution(){ cin >> s ; } void ans(){ stack<char> st; for(auto c : s){ if(c == '{' || c == '[' || c == '(' || c == '<'){ st.push(c); } else{ if(st.empty()){ st.push(c); break; } if(c == '}' && st.top() == '{'){ st.pop(); } else if(c == ']' && st.top() == '['){ st.pop(); } else if(c == ')' && st.top() == '('){ st.pop(); } else if(c == '>' && st.top() == '<'){ st.pop(); } else{ st.push(c); break; } } } cout << (st.empty() ? "Y" : "N") << endl; } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while(t--){ Solution s; s.ans(); } return 0; } ```