C - Parentheses Balance UVA - 673

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liujie2232692543/article/details/90205217

我的代码:(正确的)

#include <iostream>
#include <algorithm>
#include <string.h>
#include <math.h>
#include <stack>

using namespace std;
char a[200005];

stack<char>s;
stack<char>ch;
//void prtstk(){
//	while(!s.empty()){
//		ch.push(s.top());
//		s.pop();
//	}
//	while(!ch.empty()){
//		cout<<ch.top();
//		s.push(ch.top());
//		ch.pop();
//	}
//	cout<<endl;
//}
int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{
		getchar();
		for(int i=0;i<n;i++)
		{
			while(!s.empty())
			{
				s.pop();
			}
		//	cout<<s.top()<<endl;
			gets(a);
			int len = strlen(a);
			for(int j=0;j<len;j++)
			{
				if(s.empty())
				{
					s.push(a[j]);
				}
				else
				{
					if((s.top()=='['&&a[j]==']')||(s.top()=='('&&a[j]==')'))
					{
						s.pop();
					}
					else
					{
						s.push(a[j]);
						
					}
				}
			//	prtstk();
			}
			if(s.empty())
			{
				printf("Yes\n");
			}
			else
			{
				printf("No\n");
			}
		}
	}
	return 0;
}

这道题有一个函数是中哥教我的,可以用来调试,打印栈中的元素:

void prtstk(){
	while(!s.empty()){
		ch.push(s.top());
		s.pop();
	}
	while(!ch.empty()){
		cout<<ch.top();
		s.push(ch.top());
		ch.pop();
	}
	cout<<endl;
}

这道题目有一个非常大的坑点!!!!!!!!!!!!!!(ps:这个bug很强大)

我原先的代码:(错误的)

#include <iostream>
#include <algorithm>
#include <string.h>
#include <math.h>
#include <stack>

using namespace std;
char a[200005];

stack<char>s;
stack<char>ch;
//void prtstk(){
//	while(!s.empty()){
//		ch.push(s.top());
//		s.pop();
//	}
//	while(!ch.empty()){
//		cout<<ch.top();
//		s.push(ch.top());
//		ch.pop();
//	}
//	cout<<endl;
//}
int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{
		for(int i=0;i<n;i++)
		{
			while(!s.empty())
			{
				s.pop();
			}
		//	cout<<s.top()<<endl;
			scanf("%s",a);
			int len = strlen(a);
			for(int j=0;j<len;j++)
			{
				if(s.empty())
				{
					s.push(a[j]);
				}
				else
				{
					if((s.top()=='['&&a[j]==']')||(s.top()=='('&&a[j]==')'))
					{
						s.pop();
					}
					else
					{
						s.push(a[j]);
					}
				}
			//	prtstk();
			}
			if(s.empty())
			{
				printf("Yes\n");
			}
			else
			{
				printf("No\n");
			}
		}
	}
	return 0;
}

这道题目中:如果输入空串,应该输出Yes,然错误的代码什么也没有输出,所以应该用gets进行输入字符串,在之前加getchar(),接收换行。

猜你喜欢

转载自blog.csdn.net/liujie2232692543/article/details/90205217