括号匹配(C语言)
问题描述:
假设一个算术表达式中可以包含三种括号:圆括号"(" 和")",方括号"[“和”]“和花括号”{“和”}",
且这三种括号可按任意的次序嵌套使用,如:[{}[]]。
给定一个括号序列,请判定该括号序列是否合法。
输入:
输入仅一行由括号构成的字符序列,序列长度不超过1000.
输出:
在单独的一行中输出yes或者no,表示括号序列是否合法。
输入样列:
[{}[]][]()
输出样例:
yes
正确代码:
#include<stdio.h>
#include<stdlib.h>
typedef char ElementType;
char a[]={'{','[','(','+'};
int f(char x)
{
if(x=='}') return 0;
if(x==']') return 1;
if(x==')') return 2;
return 3;
}
typedef struct
{
ElementType *array; //存放栈数据
int top; //栈顶
int capacity; //容量
} SeqStack;
int main()
{
SeqStack *s;
s=(SeqStack*)malloc(sizeof(SeqStack));
s->array=(ElementType*)malloc(1005*sizeof(ElementType));
s->capacity=1005;
s->top=-1;
char x,t[1000];
// 这里直接读入一串,文章下面提供一个错误的案例scanf("%c",&x)
scanf("%s",t);
for(int i=0;t[i]!='\0';i++){
x=t[i];
// 栈为空 或 括号不匹配(当f()函数返回 3时,说明输入的书左括号,同样不匹配)
if(s->top==-1||s->array[s->top]!=a[f(x)]) {
s->top++;
s->array[s->top]=x;
}
// 括号匹配出栈
else{
s->top--;
}
}
if(s->top>-1)
printf("no\n");
else
printf("yes\n");
return 0;
}
错误代码:
#include<stdio.h>
#include<stdlib.h>
typedef char ElementType;
char a[]={'{','[','(','+'};
int f(char x)
{
if(x=='}') return 0;
if(x==']') return 1;
if(x==')') return 2;
return 3;
}
typedef struct
{
ElementType *array; //存放栈数据
int top; //栈顶
int capacity; //容量
} SeqStack;
int main()
{
SeqStack *s;
s=(SeqStack*)malloc(sizeof(SeqStack));
s->array=(ElementType*)malloc(1005*sizeof(ElementType));
s->capacity=1005;
s->top=-1;
char x;
while(1){
scanf("%c",&x);
if(x=='\n'||x=='\0'){
break;
}
// 栈为空 或 括号不匹配(当f()函数返回 3时,说明输入的书左括号,同样不匹配)
if(s->top==-1||s->array[s->top]!=a[f(x)]) {
s->top++;
s->array[s->top]=x;
}
// 括号匹配出栈
else{
s->top--;
}
}
if(s->top>-1)
printf("no\n");
else
printf("yes\n");
return 0;
}