# 題目: UVa 673 - Parentheses Balance
# 題目說明
有一個包含 [ 、 ] 、 ( 、 ) 這四種符號的字串,你需要判斷此字串是否符合以下規則
- 空字串為
correct - 如果
A與B皆為correct,AB為correct - 如果
A為correct,那[A]與(A)也為correct
INPUT:
第一行為一個整數 T ,代表有幾筆資料
每筆資料輸入一串字串
OUTPUT:
結果為 correct 輸出 Yes ,否則輸出 No
# 解題方法
使用 stack
當輸入為 ] 、 ) 時,判斷 stack.top() 是否為 [ 、 ( ,是則 pop
其餘狀況皆 push 進 stack
最後判斷 stack 是否為空即可
# 參考程式碼
#include <iostream> | |
#include <stack> | |
#include <string> | |
using namespace std; | |
int main() | |
{ | |
ios::sync_with_stdio(false); | |
cin.tie(nullptr); | |
cout.tie(nullptr); | |
int T; | |
string str; | |
cin >> T; | |
cin.ignore(); | |
while (T--) | |
{ | |
stack<char> S; | |
getline(cin, str); | |
for (auto& c : str) | |
{ | |
if (c == ']') | |
{ | |
if (!S.empty() && S.top() == '[') S.pop(); | |
else (S.emplace(c)); | |
} | |
else if (c == ')') | |
{ | |
if (!S.empty() && S.top() == '(') S.pop(); | |
else (S.emplace(c)); | |
} | |
else S.emplace(c); | |
} | |
cout << (S.empty() ? "Yes" : "No") << "\n"; | |
} | |
return 0; | |
} |