天天看點

UVa673_ Parentheses Balance

題目:點選打開連結

思路:遇到“(”或者“["就入棧,遇到")"或“]"就看棧頂元素是否比對,不比對就ok=0;然後繼續下一組資料。但這樣必須判斷最後是否為空串,如測試樣列((() 輸出No。

#define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
#include<stack>
#include<vector>
#include<queue>
#include<cstring>
#include<sstream>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;

stack<char> stk;

int main(){
	//freopen("random_numbers.txt","r",stdin);
	int T;
	cin >> T;
	getchar();
	while (T--){
		string str;
		getline(cin, str);//空行也得輸出Yes
		int ok = 1;
		if (str.length() % 2){
			cout << "No\n"; continue;
		}
		while (!stk.empty()) stk.pop();
		int len = str.length();
		for (int i = 0; i < len; i++){
			if (str[i] == '(' || str[i] == '[')
				stk.push(str[i]);
			else{
				if (str[i] == ']'&& !stk.empty()&&stk.top() == '[')
					stk.pop();
				else if (str[i] == ')'&&!stk.empty()&&stk.top() == '(')
					stk.pop();
				else{
					ok = 0; break;
				}
			}
		}
		if (ok&&stk.empty()) cout<<"Yes\n";  
		else cout << "No\n";
	}
	return 0;
}