We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
importjava.util.*;classSolution{publicstaticvoidmain(String[]argh){Scannersc=newScanner(System.in);while(sc.hasNext()){Stringinput=sc.next();// Create stack to track opening bracketsStack<Character>stack=newStack<>();// Loop through the characters of the stringbooleanisValid=true;// Track if the string is validfor(inti=0;i<input.length();i++){Characterch=input.charAt(i);// If it's an opening bracket, push to the stackif(ch=='{'||ch=='('||ch=='['){stack.push(ch);}// If it's a closing bracketelseif(ch=='}'||ch==')'||ch==']'){// If stack is empty, it's an unmatched closing bracketif(stack.isEmpty()){isValid=false;break;// Exit the loop early}// Pop from stack and check if the brackets matchchartop=stack.pop();if((ch=='}'&&top!='{')||(ch==')'&&top!='(')||(ch==']'&&top!='[')){isValid=false;break;// Exit the loop early}}}// After processing all characters, the stack must be emptyif(isValid&&stack.isEmpty()){System.out.println("true");}else{System.out.println("false");}}}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Java Stack
You are viewing a single comment's thread. Return to all comments →