1-先设置一个空栈,用来存放暂未匹配的括号;
2-报错:
a.空栈时,数组当前数据为右括号;
b.栈非空,栈顶指针指向的数据与数组当前数据不匹配;
c.算法结束时,栈应为空,否则括号序列不匹配;
3-若数组当前数据为左括号,将数据压入栈内;
代码如下:
#include2.括号匹配#include #include #define MaxSize 50 //定义一个顺序栈 typedef struct { //顺序栈需定义存放数据的数组以及栈顶指针 char data[MaxSize]; int top; }SqStack; //初始化栈 void InitStack(SqStack &S) { S.top = -1; } //判栈空 bool Empty(SqStack S) { return S.top == -1; } //入栈 bool Push(SqStack& S, char e) { //入栈判栈满 if (S.top == MaxSize - 1) return false; S.data[++S.top] = e; return true; } //出栈 bool Pop(SqStack& S, char& e) { //出栈判栈空 if (S.top == -1) return false; e = S.data[S.top--]; return true; } //取栈顶 bool GetTop(SqStack S, char& e) { if (S.top == -1) return false; e = S.data[S.top]; return true; }
代码如下:
//括号匹配问题
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 (Empty(S))
return false;
//若栈不为空,则分三种情况
char EmleTop;
Pop(S, EmleTop);
if ((str[i] == '}' && EmleTop != '{') || (str[i] == ']' && EmleTop != '[') || (str[i] == ')' && EmleTop != '('))
return false;
}
}
return Empty(S);
}
//main函数
int main() {
//静态分配数组
char array[10] = { '{','[','(',')','[',']',']','}','[',']'};
int length = 10;
for (int i = 0;i <= length;i++) {
printf("%c",array[i]);
printf(" ");
}
printf("n");
if (BracketCheck(array, length))
printf("匹配成功n");
else
printf("匹配失败n");
return 0;
}
三、思考
如何用动态分配数组编写此算法?



