您的位置:首页 > 其它

UVa 673 (括号配对) Parentheses Balance

2015-02-03 23:44 375 查看
本来是当做水题来做的,后来发现这道题略坑。

首先输入的字符串可能是空串,所以我用了gets函数,紧接着就被scanf("%d", &n)后面的换行符坑掉了。

于是乎再加一句getchar()

#include <cstdio>
#include <stack>
#include <cstring>
using namespace std;

const int maxn = 150;
char s[maxn];

bool ok(const char& c1, const char& c2)
{
if(c1 == '(' && c2 == ')') return true;
if(c1 == '[' && c2 == ']') return true;
return false;
}

int main()
{
//freopen("in.txt", "r", stdin);

int n;
scanf("%d", &n); getchar();
while(n--)
{
gets(s);
stack<char> S;
while(!S.empty()) S.pop();
int l = strlen(s);
if(l % 2 != 0)
{
puts("No");
continue;
}
bool flag = true;
for(int i = 0; i < l; ++i)
{
if(s[i] == '(' || s[i] == '[') S.push(s[i]);
else
{
if(S.empty()) { flag = false; break; }
else if(ok(S.top(), s[i])) S.pop();
else { flag = false; break; }
}
}
if(!S.empty()) flag = false;
printf("%s\n", flag ? "Yes" : "No");
}

return 0;
}


代码君
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: