5 Dec 2017

Write a program in java to check parenthesis validation through Stack.


import java.util.*;
class Parenthesis
{
          public static void main(String[] args)
          {
                   System.out.println("enter parenthesis");
                   String input=new Scanner(System.in).next();
                   Stack st=new Stack();
                   for(int i=0;i<input.length();i++)
                   {
                             if(st.isEmpty())
                                      st.push(input.charAt(i));
                             else
                                      switch(input.charAt(i))
                                      {
                                                case '}' :st.pop();break;
                                                case ']' :st.pop();break;
                                                case ')' :st.pop();break;
                                                default  :st.push(input.charAt(i));
                                      }
                   }
                   if(st.isEmpty())
                             System.out.println("balanced");
                   else
                             System.out.println("not balanced");
          }
}

Output: