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;
}
}
其实也有钻空子的算法——纯计数,这题的样例没有
)(
这种情况,所以计数法也可通过