文章

49

粉丝

140

获赞

27

访问

16.3k

头像
括号匹配 题解:
P1501 西北工业大学2015机试题
发布于2024年2月18日 18:28
阅读数 231

#include<iostream>
#include <string.h>
using namespace std;
int main(){
	char a[10005],stack[10005];
	for(int i=0;i<10005;i++){
		a[i]=0;
	stack[i]=0;
	}
	int num=0,top=-1;
	gets(a);
	for(int i=0;i<strlen(a);i++)
	{  if(num>0){
		char now=stack[top];//收集现在的栈顶元素
		if((now=='('&&a[i]==')')||(now=='['&&a[i]==']')){//匹配到当前现在的a数组中的元素
			top--;//出栈
			num--;//栈中元素减少1个
		}
		else{
			stack[++top]=a[i];//入栈,栈中元素增加
			num++;
		}
	}
	//栈中元素不够====================
	else {
 top++;
stack[top]=a[i];//入栈
num++;//栈中元素数增加
	}
	}
	if(num==0)
		cout << "YES";
	else
             cout << "NO";
	system("pause");
	return 0;
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发