#include<stdio.h>
#include <string.h>
#define MaxSize 50
typedef struct{
char 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,char x){
if(S.top==MaxSize-1)
return false;
S.data[++S.top]=x;
return true;
}
//出栈
bool Pop(SqStack &S,char &x){
if(S.top==-1)
return false;
x=S.data[S.top--];
return true;
}
//括号匹配
bool bracketCheck(char str[],int length){
SqStack S;
InitStack(S);//初始化一个栈
for(int i=0;i<length;i++){
if(str[i]=='('||str[i]=='['||str[i]=='{'){
Push(S,str[i]);
}else{
if(StackEmpty(S))
return 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 str1[]="({[]})[]";
char str2[]="({[]})[]]";
//str1测试
printf("%s\n",str1);
if(bracketCheck(str1,strlen(str1)))
printf("匹配成功!\n");
else
printf("匹配失败!\n");
//str2测试
printf("%s\n",str2);
if(bracketCheck(str2,strlen(str2)))
printf("匹配成功!\n");
else
printf("匹配失败!\n");
}
运行结果:
({[]})[]
匹配成功!
({[]})[]]
匹配失败!