PTA 括号匹配 (15 分)

给定一串字符,不超过100个字符,可能包括括号、数字、字母、标点符号、空格,编程检查这一串字符中的( ) ,[ ],{ }是否匹配。

输入格式:

输入在一行中给出一行字符串,不超过100个字符,可能包括括号、数字、字母、标点符号、空格。

输出格式:

如果括号配对,输出yes,否则输出no。

输入样例1:

sin(10+20)

输出样例1:

yes

输入样例2:

{[}]

输出样例2:

no

#include<stdio.h>
#include<string.h>

#define MaxSize 100
char str[101];
typedef enum {false, true} bool;

typedef struct SqStack{
	char data[MaxSize];
	int top;//栈顶指针 
}SqStack; 

void InitStack(SqStack *S);
void ReadChar();
bool bracketCheck(SqStack *S,char str[], int length);
bool Push(SqStack *S,char x);
bool StackEmpty(SqStack *S);
char Pop(SqStack *S);
int main()
{
	SqStack S;//声明一个顺序栈
	InitStack(&S); 
	ReadChar();
	int length;
	length = strlen(str);
	bracketCheck(&S,str,length);
}

void InitStack(SqStack *S)
{
	S->top = -1;
}

void ReadChar()
{
	gets(str);
}

bool bracketCheck(SqStack *S,char str[], int length)
{
	for(int i = 0; i<length; i++)
	{
		if(str[i]=='('||str[i]=='['||str[i]=='{')
			Push(S,str[i]);//将左括号压入栈 
		else{
			if(str[i]==')'||str[i]==']'||str[i]=='}')//扫描到右括号 
			{
				if(StackEmpty(S)==true)//如果栈为空,则返回no 
				{
					printf("no\n");
					return false;
				}
				//不为空执行以下语句
				char topElem;//栈顶元素
				topElem = Pop(S);//栈顶元素出栈
				if(str[i]==')'&&topElem!='(')
				{
					printf("no\n");
					return false;
				 } 
				else if(str[i]==']'&&topElem!='[')
				{
					printf("no\n");
					return false;
				 } 
				else if(str[i]=='}'&&topElem!='{')
				{
					printf("no\n");
					return false;
				 } 
					
			}
		}
	}
	if(StackEmpty(S)==true)
	{
		printf("yes\n");
		return true;
	}
	else
	{
		printf("no\n");
		return false;
	}
		
}

bool Push(SqStack *S,char x)
{
	S->top++;
	S->data[S->top] = x;
	return true; 
}

bool StackEmpty(SqStack *S)
{
	if(S->top == -1)
		return true;
	else
		return false;
}

char Pop(SqStack *S)
{
	char x;
	x = S->data[S->top];
	S->top--;
	return x; 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值