基础数据结构——栈(1)

给你一串字符,不超过50个字符,可能包括括号、数字、字母、标点符号、空格,你的任务是检查这一串字符中的( ) ,[ ],{ }是否匹配。

Input

输入数据有多组,每组数据不超过100个字符并含有( ,) ,[, ],{, }一个或多个。处理到文件结束。

Output

如果匹配就输出“yes”,不匹配输出“no”

Sample Input

sin(20+10)

{[}]

Sample Output

yes

no

思路:

用stack存储,只存储面向右的括号,如果有面向左的括号,那么就判断,如果stack的最后一个于这是一对那么,去除stack的最后一个,因为无论括号怎样,向左的括号类型一定是与你最近存储的向右的括号是配对的,举个列子:((({}))),((}(({)))和(){()}。你也可以自己画画,无论怎样变化,都不能改变你最近存储的向右的括号一定与你现在碰上的向左的括号配对,如果不是那么一定是错的,break就行了。

代码:

错误的:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<iomanip>
#include<cstring>
#include<string>
#include<cmath>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#define ll long long
#define mes(x,y) memset(x,y,sizeof(x))
using namespace std;
int main(){
	stack<char>sta;string s;int flag=0;
	while(cin>>s){
		flag=0;
	for(int i=0;i<s.length();i++){
		if(s[i]=='('||s[i]=='['||s[i]=='{'){
			sta.push(s[i]);
		}
		else if((s[i]==')'&&sta.top()=='(')||(s[i]==']'&&sta.top()=='[')||(s[i]=='}'&&sta.top()=='{')){
			sta.pop();
		}
		else if((s[i]==')'&&sta.top()!='(')||(s[i]==']'&&sta.top()!='[')||(s[i]=='}'&&sta.top()!='{')){
			flag=1;
			break;
		}
	}
	if(flag==0)cout<<"yes"<<endl;
	else cout<<"no"<<endl; 
	}
	return 0;
}
看的出来哪里不同了吗?对,就是输入。小生就错在这里了(泪),空格也是要输入的,不要忘了。

正确的:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<iomanip>
#include<cstring>
#include<string>
#include<cmath>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#define ll long long
#define mes(x,y) memset(x,y,sizeof(x))
using namespace std;
int main(){
	stack<char>sta;string s;int flag=0;
	while(getline(cin,s)){//输入
		flag=0;
	for(int i=0;i<s.length();i++){
		if(s[i]=='('||s[i]=='['||s[i]=='{'){//存储向右的括号
			sta.push(s[i]);
		}
		else if((s[i]==')'&&sta.top()=='(')||(s[i]==']'&&sta.top()=='[')||(s[i]=='}'&&sta.top()=='{')){
			sta.pop();//最近存储的括号与碰上的相反的括号配对去除。
		}
		else if((s[i]==')'&&sta.top()!='(')||(s[i]==']'&&sta.top()!='[')||(s[i]=='}'&&sta.top()!='{')){
			flag=1;//最近存储的括号与碰上的相反的括号不配对,flag标记一下,输出时好判断。
			break;
		}
	}
	if(flag==0)cout<<"yes"<<endl;
	else cout<<"no"<<endl; 
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

GUESSERR

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

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

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

打赏作者

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

抵扣说明:

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

余额充值