#define MaxSize 10
bool bracketCheck(char str[], int length) {
char data[MaxSize];
int top = -1;
for(int i = 0; i < length; i++) {
if(str[i] == '(' || str[i] == '{' || str[i] == '{'){
if(top == MaxSize - 1)
return false;
data[++top] = str[i];
}
else{
if(top == -1)
return false;
char topElem = data[top--];
if(str[i] == ')' && topElem != '(')
return false;
if(str[i] == ']' && topElem != '[')
return false;
if(str[i] == '}' && topElem != '{')
return false;
}
}
return top == -1;
}
封装成栈
#define MaxSize 10
typedef strcut {
char data[MaxSize];
int top;
} SqStack;
void InitStack(SqStack &S)
void StackEmpty(SqStack S)
bool Push(SqStack &S, char x)
bool Pop(SqStack &S, char x)
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);
}