PTA第八章7-3 括号匹配

给定仅包含“()[]{}”六种括号的字符串,请你判断该字符串中,括号的匹配是否是合法的,也就是对应括号的数量、嵌套顺序完全正确。

输入格式:

第一行一个整数T(T<=10)

其后T行每行一个字符串只包含[{()}]六种字符(字符串长度2e5以内)

输出格式:

对于每个字符串,匹配输出Yes,否则输出No

输入样例:

2
{()[]}
([)]
输出样例:

Yes
No

THE FIRST

#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main()
{
	int T;
	cin>>T;
	string temp;
	stack<char> s1;
	int count = 0;
	while(T--)
	{
		cin>>temp;
		for(int i = 0; i <temp.size(); i++) 
		{
			if(temp[i] == '{' || temp[i] == '[' || temp[i] == '(') 
			{s1.push(temp[i]);
			}else
			if(temp[i] == '}')
			{
				if(s1.top()=='{') s1.pop();
				else 
				{
					count = 1;
					break;
				}
			}else
			if(temp[i] == ']')
			{
				if(s1.top()=='[') s1.pop();
				else 
				{
					count = 1;
					break;
				}
			}else
			if(temp[i] == ')')
			{
				if(s1.top() == '(' )s1.pop();
				else 
				{
					count = 1;
					break;
				}
			}
			if(s1.empty() )
			break;
		}
		if(count == 1) cout<<"No"<<endl;
		else cout<<"Yes"<<endl;
	 } 
	 return 0;
}

 1.刚开始temp的数据类型是string,stack也是string,但需要一个个比较括号,就相当于是字符串与字符之间比较,‘【’是字符,虽然编译没有错误,但结果都是yes。因此temp的数据类型还是string,但stack的数据类型改为char,然后用temp[i]读取字符(将temp看作vector使用)。

2.显示段错误,stack为空时,无法比较

3.第二次把empty移到前面,先判断stack是不是空在用右括号比较左括号,这次又忘记每次循环后吧count清零了,最近老是忘记清零。

4.第三次只有一个答案不对,到底是什么啊,是这个”[]{“,

5.the last: I forgot clear stack;

这种不知到循环多少次还用到数组的程序,根据需要考虑是否在循环末尾编写clear()函数

#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main()
{
	int T;
	cin>>T;
	string temp;
	stack<char> s1;
	int count = 0;
	while(T--)
	{
        count = 0;
		cin>>temp;
//         cout<<temp.size()<<endl;
		for( unsigned int i = 0; i <temp.size(); i++) 
		{
			if(temp[i] == '{' || temp[i] == '[' || temp[i] == '(') 
			{
				s1.push(temp[i]);
// 				cout<<i<<':'<<temp[i]<<endl;
				continue;
//			cout<<i<<endl;
			}else
			if(s1.empty())
			{
				count = 1;
				break;
			}
// 			cout<<i<<':'<<temp[i]<<endl;
			if(temp[i] == '}')
			{
				if(s1.top()=='{') s1.pop();
				else 
				{
					count = 1;
					break;
				}
			}else
			if(temp[i] == ']')
			{
				if(s1.top()=='[') s1.pop();
				else 
				{
					count = 1;
					break;
				}
			}else
			if(temp[i] == ')')
			{
				if(s1.top() == '(' )s1.pop();
				else 
				{
					count = 1;
					break;
				}
			} 
		}
	if(!s1.empty())
	{
		count = 1;
//		break;
	}
	if(count == 1) cout<<"No"<<endl;
	if(count == 0)cout<<"Yes"<<endl;
	while(!s1.empty())
	{
		s1.pop();
	}
	 } 
	 return 0;
}

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值