Simple Balanced Parenthesis Problem Stack implementation

This program will show how to check for the balanced Parenthesis in Java.We have used the stack implementation here with switch case.


import java.util.*;
class Solution{

public static void main(String []args)
{
Scanner sc = new Scanner(System.in);

while (sc.hasNext())
{
 String input=sc.next();
 Stack<Character> stacky = new Stack<>();
 int x=0,y=0,z=0,a=0,b=0,c=0;
for (int i = 0; i &lt; input.length(); i++)
{

switch(input.charAt(i))
{
case '[' : a++; break;
case '{' : b++;break;

case '(' : c++;
break;

case ']' :x++; break;
case '}' : y++; break;

case ')' :
z++;
break;

default: stacky.push(input.charAt(i));
}

//Complete the code

if(x==a && y==b && z==c)
{

System.out.println("true");

}
else
{
System.out.println("false");
}
}
}
}}

Hope you find this useful. For more interesting program check this link

Leave a Reply

Your email address will not be published. Required fields are marked *