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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值