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;
}


你可能感兴趣的:(栈)