括號匹配(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)不行,現在希望有大佬能夠幫忙解釋一下!

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