Thursday 22 February 2018

Check for balanced parentheses in an expression using Stack class of Java

import java.util.*;
class Solution{
 
   public static void main(String []argh)
   {
      Scanner sc = new Scanner(System.in);
      Stack<Character> stack = new Stack<>();
      while (sc.hasNext()) {
         String input=sc.next();
          for(int i=0;i<input.length();i++)
          {
              char c=input.charAt(i);
           
              if(c=='(' || c=='{' || c=='[')
                 stack.push(c);
             
             
              else if(!(stack.isEmpty())){
                    if((c==')' && stack.peek()=='(' )|| (c=='}' && stack.peek()=='{') || c==']' && stack.peek()=='[')
                        stack.pop();
                 
              }
              else stack.push(c);
             
          }
         
          if(stack.empty())
              System.out.println("true");
          else
              System.out.println("false");
          stack.clear();// IMPORTANT :)
      }
     
   
   }
}

No comments:

Post a Comment