主要思想:
用栈实现括号匹配:依次扫描所有字符,遇到左括号则入栈,遇到右括号则弹出栈顶元素检查是否匹配。
匹配失败情况:
1、左括号单身
2、右括号单身
3、左右括号不匹配
代码:
//用顺序栈实现括号匹配
#include<stdio.h>
#define MAXSIZE 10
typedef int bool;
#define true 1
#define false 0
typedef struct{
char data[MAXSIZE]; //静态数组存放栈中元素
int top; //当前栈顶元素
}SqStack;
bool bracketMatching(char str[],int length);
void initStack(SqStack *S);
bool stackEmpty(SqStack S);
bool push(SqStack *S,char e);
bool pop(SqStack *S,char *e);
bool getTop(SqStack S,char *e);
void printStack(SqStack S);
/*
用栈实现括号匹配:
依次扫描所有字符,遇到左括号则入栈,遇到右括号则弹出栈顶元素检查是否匹配。
匹配失败情况:
1、左括号单身
2、右括号单身
3、左右括号不匹配
*/
bool bracketMatching(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 e;
pop(&S,&e);
//左右括号不匹配,则匹配失败
if(str[i]==')'&&e!='('){
return false;
}
if(str[i]=='}'&&e!='{'){
return false;
}
if(str[i]==']'&&e!='['){
return false;
}
}
}
//考虑左括号是不是为0
return stackEmpty(S);
}
void initStack(SqStack *S){
S->top=-1;
}
bool stackEmpty(SqStack S){
if(S.top>=0){
return false;
}
return true;
}
bool push(SqStack *S,char e){
if(S->top==MAXSIZE-1){
return false;
}
S->top=S->top+1;
S->data[S->top]=e;
return true;
}
bool pop(SqStack *S,char *e){
if(S->top==-1){
return false;
}
*e=S->data[S->top];
S->top=S->top-1;
return true;
}
bool getTop(SqStack S,char *e){
if(S.top==-1){
return false;
}
*e=S.data[S.top];
return true;
}
void printStack(SqStack S){
for(int i=S.top;i>=0;i--){
printf("%c ",S.data[i]);
}
printf("\n");
}
int main(){
char e;
char str[]={'[','{','[','(',')',')','}',']'};
int lenth=sizeof(str)/sizeof(char);
for(int i=0;i<lenth;i++){
printf("%c ",str[i]);
}
printf("\n");
if(bracketMatching(str,lenth)){
printf("括号匹配\n");
}else{
printf("括号不匹配\n");
}
return 0;
}
运行结果: