括号匹配(C语言)(知识点:数据结构栈的运用)

括号匹配(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;
}

代码对比:

在这里插入图片描述

在这里插入图片描述

对比就可以发现这个代码,就是上面两个循环读入数据不同,但我还是不知道下面那个scanf("%c",&x)不行,现在希望有大佬能够帮忙解释一下!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章