Java Stack HackerRank

 import java.util.*;

class Solution{
    
    public static void main(String []argh)
    {
        Scanner sc = new Scanner(System.in);
        /*String s=sc.next();
        /*ArrayList<String>aa=new ArrayList<String>();
         ArrayList<String>ab=new ArrayList<String>();*/
        Stack<Character>stack=new Stack<Character>();
        
            while (sc.hasNext()) {
                
                String s=sc.next();
                //aa.add(str);
           
            for(int i=0;i<s.length();i++){
                
                //int count=0;
                //String input=aa.get(i1);
                //for(int i=0;i<input.length();i++){
                    if(stack.isEmpty()){
                        stack.push(s.charAt(i));
                    }
                    else if(stack.peek()=='{' && s.charAt(i)=='}'){
                        stack.pop();
                    }
                    else if(stack.peek()=='(' && s.charAt(i)==')'){
                         stack.pop();
                    }
                    else if(stack.peek()=='[' && s.charAt(i)==']'){
                        stack.pop();
                    }
                    else{
                        stack.push(s.charAt(i));
                    }
                    
               // }
            }
                if(stack.isEmpty()){
                    System.out.println("true");
                    //ab.add("true");
                }
                else{
                    System.out.println("false"); 
                    
                    //ab.add("false");  
                }
                while(!stack.isEmpty()){
                    stack.pop();
                }
                
        }
            //}
            
            /*for(int j=0;j<ab.size();j++){
                System.out.println(ab.get(j)+" ");
            }*/
        
    }
}


Time:O(N)

Space:O(N)[As Stack Is Used]

Approach:

    We will insert the elements into the stack. If stack. peek() is conjugate of the incoming character
of string then we will pop the peek of the stack and we will check this for all the parenthesis described.
In last if we get the stack empty it means the string was balanced else unbalanced.


Thanks For Reading😇.

"Share Further To Help Other And Enhance Knowledge.😊"



Comments

Popular posts from this blog

Solutions Of Practice Questions Dated 01-06-2022

CODEFORCES SPY DETECTED ROUND 713

Maximum Winning Score Geeks For Geeks