您的位置:首页 > 其它

UVa673_ Parentheses Balance

2015-03-24 18:43 375 查看
题目:点击打开链接

思路:遇到“(”或者“["就入栈,遇到")"或“]"就看栈顶元素是否匹配,不匹配就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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: