I am trying to solve the problem of brackets matching i.e. given a sequence of opening and closing parenthesis exp
, consisting of (
or )
, square brackets [
or ]
or curly braces }
or {
, I need to tell if the given sequence is balanced or not.
Sample Input1:
exp = "[]{}()"
Sample Output1:
Match Successfull....!
----------
Sample Input2:
exp = "[]{(]}()"
Sample Output1:
Match not Successfull....!
PS: empty string is considered a balanced string.
Below is the code written in C where I tried to implement a stack using struct
. I implemented the all the necessary function of a stack i.e., pop()
, push()
, isFull()
etc.
However, I am getting segmentation fault. Please help me rectify the error.
#include <stdio.h>
#include <stdlib.h>
struct stack {
int size;
int top;
char *arr;
};
int isEmpty(struct stack *ptr) {
if (ptr->top == -1)
{
return 1;
}
return 0;
}
int isFull(struct stack *ptr) {
if (ptr->top == ptr->size - 1)
{
return 1;
}
return 0;
}
int push(struct stack *ptr, char val) {
if (isFull(ptr))
{
return 1;
}
else
{
ptr->top++;
ptr->arr[ptr->top] = val;
}
}
int pop(struct stack *ptr) {
char val;
if (isEmpty(ptr))
{
return 1;
}
else
{
ptr->top--;
val = ptr->arr[ptr->top];
return val;
}
}
int match(char a, char b) {
if (a == '{' && b == '}' || a == '(' && b == ')' || a == '[' && b == ']')
{
return 1;
}
else
{
return 0;
}
}
int parMatch(char *exp) {
struct stack *s = malloc(sizeof(struct stack));
s->arr = (char *)malloc(s->size * sizeof(char));
s->size = 100;
s->top = -1;
char char_pop;
for (int i = 0; exp[i] = '\0'; i++)
{
if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[')
{
push(s, exp[i]);
}
else if (exp[i] == ')' || exp[i] == '}' || exp[i] == ']')
{
return 0;
}
char_pop = pop(s);
if (!match(char_pop, exp[i]))
{
return 0;
}
}
if (isEmpty(s))
{
return 1;
}
else
{
return 0;
}
}
int main() {
char *exp = "[]{}()";
if (parMatch(exp))
{
printf("Match Successfull....!");
}
else
{
printf("Match not Successfull....!");
}
return 0;
}