Skip to content

Commit

Permalink
added minimum bracket reversal needed to make brackets balanced expre…
Browse files Browse the repository at this point in the history
…ssion
  • Loading branch information
GauravWalia19 committed Dec 16, 2018
1 parent d8f834a commit 17c9cfc
Show file tree
Hide file tree
Showing 3 changed files with 146 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>

/*MY OWN STACK*/
char stack[50];
int top=-1;

/**
* isEmpty()
* tells if the stack is empty or not
* @return bool
**/
bool isEmpty()
{
return top==-1;
}

/**
* size()
* returns the size of the stack
* @return int
**/
int size()
{
return top+1;
}

/**
* push(char)
* push char to the top of the stack
**/
void push(char ch)
{
stack[++top]=ch;
}

/**
* pop()
* deletes and returns the top element of the stack
* @return char
**/
char pop()
{
if(isEmpty())
{
return '0';
}
char temp = stack[top];
top--;
return temp;
}

/**
* peek()
* returns the top element of the stack
* @return char
**/
char peek()
{
return stack[top];
}

/**
* print()
* prints the stack
**/
void print()
{
for(int i=0;i<=top;i++)
{
printf("%c ",stack[i]);
}
printf("\n");
}

/*MAIN PROGRAM*/
int main()
{
int T;
scanf("%d",&T);
while(T-->0)
{
char str[50];
scanf("%s",str);
if(strlen(str)%2)
{
printf("-1\n");
}
else
{
//balancing the brackets
for(register int i=0;i<strlen(str);i++)
{
if(str[i]==']' && !isEmpty())
{
if(peek()=='[')
{
pop();
}
else
{
push(str[i]);
}
}
else
{
push(str[i]);
}
}
//checking balancing
//remaining left in the stack
//counting the brackets
int a=0; //'['
int len = size();
while(!isEmpty() && peek()=='[')
{
pop();
a++;
}
int b=len-a;
double a1 = (double)a/2;
double b1 = (double)b/2;
int result= (int)ceil(a1) + (int)ceil(b1);
printf("%d\n",result);
}
}
return 0;
}
8 changes: 8 additions & 0 deletions C/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@
* UNROLLED LINKED LIST
* SKIP LIST

#### STACKS

* FIXED ARRAY STACK
* DYNAMIC ARRAY STACK
* LINKED STACK
* MISC
* [Minimum bracket reversal for balanced expression](Data-Structures/STACKS/MISC-STACKS/minimum_bracket_reversal_for_balanced_expression.c)

#### HEAPS

* [1D ARRAYS USING HEAPS](Data-Structures/HEAPS/dynamicarray.c)
Expand Down
7 changes: 7 additions & 0 deletions datastructures.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,13 @@ Indexer for Data Structures Lover

#### MISC STACKS

##### Minimum bracket reversal for making brackets balanced

* blog
* docs
* implementation
* [C](C/Data-Structures/STACKS/MISC-STACKS/minimum_bracket_reversal_for_balanced_expression.c)

##### TWO WAY STACK

* blog
Expand Down

0 comments on commit 17c9cfc

Please sign in to comment.