NYOJ-2 括号配对问题 -- 数据结构_堆栈

以前做过的,现在整理一下,主要是堆栈的使用

1.碰到左括号就入栈,碰到右括号就从栈里弹出一个和当前比配,匹配失败就肯定是NO了;

2.如果右括号弹栈的时候栈空,则说明之前没有和右括号匹配的左括号了,这结果也是NO;

3.如果字符串处理完了栈里面还有符号,结果为NO;

如果处理到最后都没有出现NO的情况,则输出YES;

注意两种括号要区别开

 
#include<iostream>
#include<stack>
#include<stdio.h>
using namespace std;

stack<char> stack_ch;

int main()
{
	int num;
	char ch;
	int flag;
	cin>> num;
	getchar();
	while(num--)
	{
		flag = 0;
		while(!stack_ch.empty ())
		{
			stack_ch.pop();
		}
		while((ch = getchar()) != '\n')
		{
			if(ch == '[')
				stack_ch.push (ch);
			else if(ch == '(')
				stack_ch.push (ch);
			else if(ch == ']')
			{
				if(stack_ch.empty())
					flag =1 ;
				else if(stack_ch.top() == '[')
					stack_ch.pop ();
				else
					flag = 1;
			}
			else if(ch == ')')
			{
				if(stack_ch.empty ())
					flag = 1;
				else if(stack_ch.top() == '(')
					stack_ch.pop();
				else
					flag = 1;
			}
		}
		if(flag == 1)
			cout<<"No"<<endl;
		else
			cout<<"Yes"<<endl;	
	}
	return 0;
}        



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

勇敢的炮灰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值