Check If Brackets are Balanced Algo

By   Tewodros   Date Posted: Oct. 4, 2021  Hits: 879   Category:  Algorithm   Total Comment: 0             A+ A-


side

Given a string with several opening and closing brackets, we want to check if the brackets are balanced when every opening bracket is closed.

Examples: 

( ( ) ( ( ) ) )  is balanced whereas ( ) ) is not. 

( ) ( ) ( ) ( ) is balanced whereas ( ( ) ( ) ) ) is not

) ) ( (  is not balanced. 

Solutions:

This is a perfect fit for our stack data structure.

  1. Every time we see the opening bracket, we can push it to the stack. Also if we see a closing bracket before we see an opening bracket, we return false / not balanced.
  2. Every time we see a closing bracket, we pop the opening bracket we already pushed if the stack is not empty
  3. Finally, if we still have left overs in the stack after we are done through the string it means there is a closing bracket missing.

               

               Stack<string> stack = new Stack<string>();

               for (int i = 0; i < A.Length; i++)   {

                   if (A[i] == '(')

                       stack.Push(A[i].ToString());

                   else     {

                       if (stack.Count != 0)

                           stack.Pop();

                       else

                           return false;

                   }

               }

               if (stack.Count == 0)

                   return true;

 


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* ldxrtf

Back to Top