Balanced parentheses

By   Tewodros   Date Posted: Oct. 27, 2023  Hits: 418   Category:  Algorithm   Total Comment: 0             A+ A-


side

Given a string with a list of parentheses composed of { [ ( } ] ) we want to return true if it is balanced. The last bracket that is opened must be the first one to be closed.

Example of valid parentheses

{[()]}

{}[]()

Solution:

Since the last bracket that is opened must also be the first one to be closed, it makes sense to use stack data structure.

public class Solution {

   public bool IsValid(string s) {

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

       if(s[0] == ')' || s[0] == '}' || s[0] == ']') return false;      

 

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

       {

           if(s[i] == '(' || s[i] == '{' || s[i] == '[')

                 stack.Push(s[i]);

           

           else if(s[i] == ')' && stack.Count !=0)

           {

               char ch = stack.Peek();

               if(ch == '(')               

                   stack.Pop();

               

                else return false;

           }

           else if(s[i] == ']' && stack.Count !=0)

           {

               char ch = stack.Peek();

               if(ch == '[')               

                   stack.Pop();         

 

               else return false;

           }

           else if(s[i] == '}' && stack.Count !=0)

           {

               char ch = stack.Peek();

               if(ch == '{')

                       stack.Pop();               

                else return false;

           }

           else

            return false;

       }

 

       if(stack.Count == 0)

           return true;

       else

          return false;

   }

}


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:* nybjnd

Back to Top