ny 括号配对问题 【栈】

题目链接:http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=2

时间限制:3000 ms  |  内存限制:65535 KB

难度:3

输入

第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[", "]", "(", ")" 四种字符

输出

每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No

样例输入

3
[(])
(])
([[]()])

样例输出

No
No
Yes

描述

现在,有一行括号序列,请你检查这行括号是否配对。

思路:括号匹配,我刚开始的一个代码一直出现runtimeError,分析原因就是因为出现了栈空还要继续用的情况,先贴上错误的代码:

#include<stdio.h>
#include<string.h>
#include<stack>
char s[10002];
using namespace std;
int main()
{   
    stack<char>sta;
	int t;
	scanf("%d",&t);
	while(t--)
	{    
	    while(!sta.empty())
	       sta.pop();
		scanf("%s",s);
		int l=strlen(s);
		if(s[0]==']'||s[0]==')')
		{
			printf("No\n");
			continue;
		 } 
		sta.push(s[0]);
		for(int i=1;i<l;i++)
		{   //受限于下面这个if语句,想想为啥 
		    if((s[i]==']'&&sta.top()=='[' )|| (s[i]==')'&&sta.top()=='(') )  
					sta.pop();
			else
			        sta.push(s[i]);
		}
		if(!sta.empty())
		  printf("No\n");
		else
		  printf("Yes\n");
	}
	return 0;
}        

我为了避免上面的那个情况,在栈顶又加入了一个任意(只要不是题目涉及的都可)字符‘1’,这样上面代码的问题就解决了 感觉自己好zz 代码如下:

#include<stdio.h>
#include<string.h>
#include<stack>
using namespace std;
char s[100002];
int main()
{   
    stack<char>sta;
	int t;
	scanf("%d",&t);
	while(t--)
	{   
		scanf("%s",s);
		int l=strlen(s);
		sta.push('1');
		if(s[0]==']'||s[0]==')')
		{
			printf("No\n");
			continue;
		}
		sta.push(s[0]);
		for(int i=1;i<l;i++)
		{
		    if((s[i]==']'&&sta.top()=='[' )|| (s[i]==')'&&sta.top()=='(') )
					sta.pop();
			else
			        sta.push(s[i]);
		}
		if(sta.top()!='1')
		  printf("No\n");
		else
		  printf("Yes\n");
		while(sta.top()!='1')
	       sta.pop();
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/LOOKQAQ/article/details/81603654
今日推荐