总时间限制:
1000ms
内存限制:
1000kB
描述
假设表达式中只包含三种括号:圆括号、方括号和花括号,它们可相互嵌套,如([{}])或({[][()]})等均为正确的格式,而{[]})}或{[()]或([]}均为不正确的格式.
输入一串括号
如果输入的右括号多余,输出:Extra right brackets
如果输入的左括号多余, 输出:Extra left brackets
如果输入的括号不匹配,输出:Brackets not match
如果输入的括号匹配,输出:Brackets match
输入
{{{{)))
输出
Brackets not match
样例输入
{([)]}
样例输出
Brackets not match
提示
利用栈结构
#include”stdio.h”
#include”stdlib.h”
#define false -1
#define true 1
#define STAC 100
#define STA 10
typedef char Elemtype;
typedef struct {
Elemtype *base;
Elemtype *top;
int stacksize;
}tack;
int InitStack(tack *S) {//构建一个空栈
S->base = (Elemtype *)malloc(STAC * sizeof(Elemtype));
if (!S->base) return false;
S->stacksize = STAC;//分配空间大小
S->top = S->base;
return true;
}
int Push(tack *S, Elemtype e) {//插入到栈顶
//判D断是否溢出
if (S->top – S->base >= S->stacksize) {
S->base = (Elemtype *)realloc(S->base, (S->stacksize + STA) * sizeof(Elemtype));
if (!S->base) return false;
S->top = S->base + S->stacksize;
S->stacksize += STA;
}
S->top++;
*S->top = e;
return true;
}
int main() {
int i, n;
char e;
tack la;
InitStack(&la);
for (i = 0;; i++) {
scanf(“%c”, &e);
if (e == ‘\n’)break;
Push(&la, e);
while (*(la.top – 1) == *la.top – 1 || *(la.top – 1) == *la.top – 2)
la.top = la.top – 2;
}
if (la.base == la.top) printf(“Brackets match\n”);
else if (*la.top == ‘(‘ || *la.top == ‘{‘ || *la.top == ‘[‘) {
while (la.base != la.top) {
la.top–;
if (*la.top == ‘)’ || *la.top == ‘}’ || *la.top == ‘]’) {
printf(“Brackets not match\n”);
return 0;
}
}
printf(“Extra left brackets”);
}
else if (*la.top == ‘)’ || *la.top == ‘}’ || *la.top == ‘]’) {
while (la.base != la.top) {
la.top–;
if (*la.top == ‘(‘ || *la.top == ‘{‘ || *la.top == ‘[‘) {
printf(“Brackets not match\n”);
return 0;
}
}
printf(“Extra right brackets\n”);
}
return 0;
}