栈的括号匹配应用

目录

核心思想:

代码:

下一篇:栈的表达式求值问题


核心思想:

从左往右扫描字符串,如果遇到左括号就入栈,右括号则弹出栈顶元素并检查是否匹配

匹配失败的情况:1、字符串扫描完后栈不空2、还没扫描完栈空3、左右括号不匹配

代码:

#include<bits/stdc++.h>
using namespace std;
#define MaxSize 30
typedef struct{
	char data[MaxSize];
	int top;
}SqStack;
void InitStack(SqStack &S){
	S.top=0;
}
bool StackEmpty(SqStack S){
	return S.top==0;
}
bool Push(SqStack &S,char x){
	if(S.top==MaxSize)return false;
	S.data[S.top]=x;
	S.top++;
	return true;
}
bool Pop(SqStack &S,char &x){
	if(S.top==0)return false;
	S.top=S.top-1;
	x=S.data[S.top];
	return true;
}
bool bracketCheck(char str[]){
	SqStack S;
	InitStack(S);
	int length=strlen(str);//也可以传参一个长度进来 
	for(int i=0;i<length;i++){
		if(str[i]=='('||str[i]=='['||str[i]=='{'){//遇到左括号就进栈 
			Push(S,str[i]);
		}else{
			if(StackEmpty(S))return false;//有右括号且栈空则返回false 
		
		char topElem;
		Pop(S,topElem);
		//判断括号是否匹配 
		if(str[i]==')' && topElem!='(')return false;
		if(str[i]==']' && topElem!='[')return false;
		if(str[i]=='}' && topElem!='{')return false;
	}
	}
	//如果栈中有多的括号就失败了 
	return StackEmpty(S);
}
int main(){
	char s[]="{
   
   {
   
   {(()}}";
	if(bracketCheck(s))
		cout<<"匹配成功!\n";
	else
		cout<<"匹配失败!";
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_46919419/article/details/114880658