将所有左括号进栈,在遇到右括号时取出栈顶元素,若匹配则出栈栈顶元素,进行一次判断,若不匹配则括号不匹配。
//"标头.h"
#pragma once
#include<iostream>
#define Max 100
using namespace std;
typedef char Elem;
typedef struct SqStack
{
Elem data[Max];
int top;
}Stack;
void InitStack(Stack *s)//初始化
{
s = new Stack;
s->top = -1;
}
bool Push(Stack *p,Elem e)//进栈
{
if (p->top == Max - 1)
return false;
p->top++;
p->data[p->top] = e;
return true;
}
bool Pop(Stack *p, Elem &e)//出栈
{
if (p->top == -1)
return false;
e = p->data[p->top];
p->top--;
return true;
}
bool GetTop(Stack *p, Elem &e)//取栈顶指针
{
if (p->top == -1)
return false;
e = p->data[p->top];
return true;
}
bool Empty(Stack *s)//判断栈是否为空
{
return (s->top == -1);
}
void Destory(Stack *s)//销毁
{
free(s);
}
bool PanDuan(char *str)//判断是否匹配
{
bool match = true;
Elem e;
Stack *s;
s = new Stack;
s->top = -1;
while (*str != '\0'&&match)
{
switch (*str)
{
case '(':
case '{':
case '[':
Push(s, *str);//将左括号全部进栈
break;
case ')':
if (GetTop(s, e) == true)
{
if (e != '(')
match = false;
else
{
Pop(s, e);
}
break;
}
else
match = false;
break;
case '}':
if (GetTop(s, e) == true)
{
if (e != '{')
match = false;
else
{
Pop(s, e);
}
break;
}
else
match = false;
break;
case ']':
if (GetTop(s, e) == true)
{
if (e != '[')
match = false;
else
{
Pop(s, e);
}
break;
}
else
match = false;
break;
default:
break;
}
*str++;
}
if (!Empty(s))
match = false;
Destory(s);
return match;
}
#include"标头.h"
int main()
{
char str[] = "[(})]";
bool match=PanDuan(str);
cout << "括号是否匹配" << match << endl;
}