括号匹配问题
( ( ( ( ) ) ) )
最后出现的左括号最先被匹配(LIFO)
( ( ( ) ) ( ) )
每出现一个右括号,就“消耗”(出栈)一个左括号
算法
流程图
代码
//万一存满,可用链栈
#define MaxSize 10 //定义栈中元素的最大个数
typedef struct{
ElemType data[MaxSize] //静态数组存放栈中元素
int top; //栈顶指针
}SqStack;
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]