您的位置:首页 > 其它

UVA 673 Parentheses Balance

2013-01-20 16:25 465 查看
链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=614

//栈的简单应用。用结构体也可以实现。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 130;

class Stack
{
public:
char str[maxn];
int top;
public:
Stack(){memset(str, 0, sizeof(str)); top = 0;};
void push(char c);
void pop();
int get_len();
void init();
}stack;

void Stack::push(char c)
{
top++;
str[top] = c;
}
void Stack::pop()
{
top--;
}
int Stack::get_len()
{
return top;
}
void Stack::init()
{
memset(str, 0, sizeof(str));
top = 0;
}

int can_match(char a, char b)
{
if ((a == '(' && b == ')') || (a == '[' && b == ']'))
{
return 1;
}
return 0;
}
int main()
{
char str[maxn];
int n, i;
while (scanf("%d",&n) == 1)
{
getchar();
while (n--)
{
gets(str);
int len = strlen(str);
if (len == 0)
{
printf("Yes\n");
continue;
}
if (len % 2 != 0)
{
printf("No\n");
continue;
}
for (i = 0; i < len; i++)
{
if (can_match(stack.str[stack.top],str[i]))
{
stack.pop();
}
else
{
stack.push(str[i]);
}
}
if (!stack.get_len())
{
printf("Yes\n");
}
else
{
printf("No\n");
}
memset(str, 0, sizeof(str));
stack.init();  //最后的遗漏点就是这里,每次要初始化一遍,但又无法调用构造函数。构造函数只是在创建类的实例的时候自动执行。
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: