基础数据结构——栈(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;
}

猜你喜欢

转载自blog.csdn.net/weixin_44417851/article/details/89190554
今日推荐