括号配对问题(nyoj 2)

问题连接

括号配对问题

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

难度:3

描述

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

输入

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

输出

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

样例输入

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

样例输出

No
No
Yes

题解:根据括号的对称性,可以使用栈的先进后出的特性,先将“(”,“[” 依次存入,如遇到另外两种则判断是否可以与将要出栈的字符相互对应起来,注意的是,入栈与出栈的是在同一循环下进行的。

代码:

#include<iostream>
#include<stack>
#include<string>
using namespace std;
bool judge(string str)
{
	stack<char>S;
	while(!S.empty())
	S.pop();
	int len=str.length();
	int i;char temp;
	for(int i=0;i<len;i++)
	{
		if(str[i]=='('||str[i]=='[')
		S.push(str[i]);
		else
		{
			if(S.empty()) return false;
			temp=S.top();
			S.pop();
			switch(str[i])
			{
				case ')':
					{
						if(temp!='(') return false;
						continue;
					}
				case ']':
					{
						if(temp!='[') return false;
						continue;
						 
					} 
			}
		}
	}
	if(!S.empty()) return false;
	return true;
}
int main()
{
	int ntest;
	cin>>ntest;
	string str;
	while(ntest--)
	{
		cin>>str;
		if(judge(str))
		cout<<"Yes"<<endl;
		else
		cout<<"No"<<endl;
	}
return 0;
}

猜你喜欢

转载自blog.csdn.net/d1183/article/details/81210406
今日推荐