Here we have to check that given string that contain brackets are balanced or not,
Ex. the given string is (({})) is balanced but string ((}) is not balance, similaraly (({}))[] is balanced
but ({)}[] is not balanced.
program:-
#include<stdio.h>
#include<stdlib.h>
struct stack
{
int top;
int capacity;
char *array;
};
// function for create stack
struct stack* creatstack(int cap)
{
struct stack *stack;
stack=(struct stack*)malloc(sizeof(struct stack));
stack->top=-1;
stack->capacity=cap;
stack->array=(char *)malloc(sizeof(char)*stack->capacity);
return(stack);
}
// function for check stack is full or not
int isfull(struct stack* stack)
{
if(stack->top==stack->capacity-1)
return(0);
else
return(1);
}
// function for check stack is empty or not
int isempty(struct stack *stack)
{
if(stack->top==-1)
return(0);
else
return(1);
}
// function for push element in to stack
void push(struct stack *stack,char item)
{
if(isfull(stack))
{
stack->top++;
stack->array[stack->top]=item;
}
}
// function for pop element from stack
char pop(struct stack *stack)
{
char item;
if(isempty(stack))
{
item=stack->array[stack->top];
stack->top--;
return(item);
}
else
return('a');
}
void main()
{
int i,flag=0,n,r,j;
char s[1000],ch;
struct stack* stack;
stack=creatstack(1000);
scanf("%d",&n);
for(j=1;j<=n;j++){
scanf("%s",s);
for(i=0;s[i];i++)
{
if(s[i]=='('||s[i]=='{'||s[i]=='[')
push(stack,s[i]);
if(s[i]==')'||s[i]=='}'||s[i]==']')
{
ch=pop(stack);
if(s[i]==')')
{
if(ch!='(')
{
printf("NO\n");
flag=1;
break;
}
}
if(s[i]=='}')
{
if(ch!='{')
{
printf("NO\n");
flag=1;
break;
}
}
if(s[i]==']')
{
if(ch!='[')
{
printf("NO\n");
flag=1;
break;
}
}
}
}
r=isempty(stack);
if(r==0&&flag==0)
printf("YES\n");
else
{
if(flag==0)
printf("NO\n");
}
flag=0;
}
getch();
}
0 Comments