20 June 2022

Stack -1 Top Programs in c#

1) Find out whether the expression is balanced or not using stack?

Input: exp = “[()]{}{[()()]()}” 
Output: Balanced

Input: exp = “[(])” 
Output: Un Balanced
Balanced 

Solution:

using System;

using System.Collections.Generic;

public class GFG {

static public void Main () {

string s="{(){(]}}";

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

foreach(var i in s) {

    if(st.Count>0 && (i==')' && st.Peek()=='(') ||

    (i=='}' && st.Peek()=='{') || (i=='[' && st.Peek()==']') )  {     st.Pop();   }

    else   {    st.Push(i);    }

}

if(st.Count==0)  Console.WriteLine("Balanced"); 

else Console.WriteLine("Un balanced");

   }

}

No comments:

Post a Comment