【数据结构】7-1 Balancing Symbols (60 分)

Balancing symbols: Check if parenthesis (), brackets[], and braces{} are balanced.

输入格式:
1 line An expression includes variables and symbols. The max length is 50.
输出格式:
1 line If all the () [] {} are balanced, then output 0. If () are not balanced, output 1; If [] not balanced, output 2; If {} not balance, output 3. If more than one symbol are not balanced, output corresponding numbers, sort them in ascending order and divided them by comma.

输入样例:
在这里给出一组输入。例如:
{a*(b-c)-x/2]
输出样例:
在这里给出相应的输出。例如:
2,3,

#include<stdio.h>
#include<stdlib.h>
#define max 100
typedef struct node{
	char data;
	struct node* next;
}*Stack;

int isEmpty(Stack s);
void pop(Stack s);
void push(Stack s,char x);
char getTop(Stack s);

main()
{
	char str[max],tmp;
	int i=0,re[3]={0},flag=0;
	Stack s=NULL;
	s=(Stack)malloc(sizeof(struct node));
	s->next=NULL;
	
	scanf("%s",str);
	while(str[i]!='\0')
	{
		switch(str[i])
		{
			case '(':
			case '[':
			case '{':
				push(s,str[i]);
				i++;
				break;
			case ')':
				//不匹配 
				if(isEmpty(s))
				{
					re[0]=1;
				}
				else
				{
					tmp=getTop(s);
					if(tmp!='(')
					{
						re[0]=1;
					}
					//匹配
					else
					{
						pop(s);
					} 
				}
				i++;
				break;
			case ']':
				//不匹配 
				if(isEmpty(s))
				{
					re[1]=1;
				}
				else
				{
					tmp=getTop(s);
					if(tmp!='[')
					{
						re[1]=1;
					}
					//匹配
					else
					{
						pop(s);
					} 
				}
				i++;
				break;
			case '}':
				//不匹配 
				if(isEmpty(s))
				{
					re[2]=1;
				}
				else
				{
					tmp=getTop(s);
					if(tmp!='{')
					{
						re[2]=1;
					}
					//匹配
					else
					{
						pop(s);
					} 
				}
				i++;
				break;
			default:
				i++;
				break;
		}
	}
	while(!isEmpty(s))
	{
		tmp=getTop(s);
		switch(tmp)
		{
			case '(':
				re[0]=1;
				break;
			case '[':
				re[1]=1;
				break;
			case '{':
				re[2]=1;
				break;
			default:
				break;
		}
		pop(s);
	}
	for(i=0;i<3;i++)
	{
		if(re[i])
		{
			printf("%d,",i+1);
			flag++;
		}
	}
	if(flag==0)
	{
		printf("0");
	}
	while(s->next!=NULL)
	{
		pop(s);
	}
	free(s);
}

int isEmpty(Stack s)
{
	if(s->next==NULL)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}
void pop(Stack s)
{
	if(s->next==NULL)
	{
		printf("\nempty stack!\n");
	}
	else
	{
		Stack tmp=s->next;
		s->next=s->next->next;
		free(tmp);
	}
}
void push(Stack s,char x)
{
	Stack c=(Stack)malloc(sizeof(struct node));
	c->data=x;
	c->next=s->next;
	s->next=c;
	c=NULL;
	free(c);
}
char getTop(Stack s)
{
	if(s->next==NULL)
	{
		printf("\nempty stack\n");
	}
	else
	{
		return s->next->data;
	}
}

其实也有钻空子的算法——纯计数,这题的样例没有
)(
这种情况,所以计数法也可通过

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值