题目描述
表达式允许三种括号:(、[、{,任意嵌套,到最后一个括号,所有括号均抵消及匹配成功。
讲解
出栈入栈讲解
括号匹配代码
(代码参考王道)
思路
遇到左括号就进栈。遇到右括号就有一个左括号出栈,与之进行匹配,成功则继续,失败则结束,直接退出
图解
四种情况:- 匹配成功(动图)
2. 左括号有剩余
3. 右括号有剩余
4. 左右括号不匹配
- 匹配成功(动图)
代码
bool bracketCheck(ElemType str[],int lenth){ SqStack S; InitStack(S); //初始化栈 for (int i = 0; i < lenth; ++i) { if (str[i]=='('||str[i]=='['||str[i]=='{'){ Push(S,str[i]); } else{ if (StackEmpty(S))return false; ElemType e; Pop(S,e); if (str[i]==')'&&e!='(')return false; if (str[i]==']'&&e!='[')return false; if (str[i]=='}'&&e!='{')return false; } } return StackEmpty(S); }
完整代码
/*
*Function:括号匹配
*/
#include "stdio.h"
#include "stdlib.h"
#define MaxSize 50
typedef char ElemType;
typedef struct {
ElemType data[MaxSize]; //存放栈中元素
int top; //栈顶指针
}SqStack;
/*初始化空栈*/
void InitStack(SqStack &S){
S.top=-1;
}
/*空栈判断*/
bool StackEmpty(SqStack S){
if (S.top==-1)
return true;
else
return false;
}
/*进栈*/
bool Push(SqStack &S,ElemType e){
if (S.top==MaxSize-1)
return false;
S.data[++S.top]=e;
return true;
}
/*出栈*/
bool Pop(SqStack &S,ElemType &e){
if (S.top==-1)
return false;
e=S.data[S.top--];
return true;
}
/*括号判断*/
bool bracketCheck(ElemType str[],int lenth){
SqStack S;
InitStack(S); //初始化栈
for (int i = 0; i < lenth; ++i) {
if (str[i]=='('||str[i]=='['||str[i]=='{'){
Push(S,str[i]);
} else{
if (StackEmpty(S))return false;
ElemType e;
Pop(S,e);
if (str[i]==')'&&e!='(')return false;
if (str[i]==']'&&e!='[')return false;
if (str[i]=='}'&&e!='{')return false;
}
}
return StackEmpty(S);
}
int main(){
int n;
printf("一共有多少个要匹配的括号:");
scanf("%d",&n);
ElemType str[n];
getchar();//回撤的时候占用了一个字符
printf("请输入要的括号:");
for (int i = 0; i < n; ++i) {
scanf("%c",&str[i]);
}
if(bracketCheck(str,n)){
printf("括号匹配成功");
}else{
printf("括号匹配失败");
}
}