普通思路
若为匹配成功的字符串,一定有一对相邻成对括号
找到最内层成对括号,将其erase掉。
一层一层erase,若最后为空,则匹配成功
缺点:erase速度太慢
用栈实现括号匹配检验
思路:
依次扫描原字符数组。
遇到左括号时,将左括号压入栈;遇到右括号时,弹出栈顶元素。
将栈顶元素与当前字符元素匹配,若不为一对则返回false
扫描数组结束后
若栈内仍有字符,则返回false
否则返回true
代码实现
#include<stdio.h>
#include<string.h>
#define MaxSize 10
typedef struct {
char data[MaxSize];
int top;
} SqStack; //顺序栈定义
void InitStack(SqStack &S) {//初始化栈
S.top=-1;
}
void Push(SqStack &S,char x) {
S.data[++S.top]=x;
}
void Pop(SqStack &S,char &x) {//栈顶元素出栈
x=S.data[S.top--];
}
bool StackEmpty(SqStack S) {//栈是否为空
if(S.top==-1)
return true;
else
return false;
}
bool bracketCheck(char str[MaxSize],int length) {
SqStack S;
InitStack(S);//初始化顺序栈
for(int i=0; i<strlen(str); 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;
}
}
if(StackEmpty(S))
return true;
else {
return false;
}
}
int main() {
char s[MaxSize]= {0};
scanf("%s",s);
if(bracketCheck(s,strlen(s))==false) {
printf("非法括号匹配\n");
}
else
printf("合法括号匹配\n");
return 0;
}