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();//Complete the codeSystem.out.println(isBalanced(input));}}privatestaticbooleanisBalanced(Stringinput){if(input.length()==0){returntrue;}Stack<Character>stack=newStack<>();for(Characterc:input.toCharArray()){switch(c){case'(':case'{':case'[':stack.add(c);break;case')':if(stack.isEmpty()||!stack.pop().equals('('))returnfalse;break;case'}':if(stack.isEmpty()||!stack.pop().equals('{'))returnfalse;break;case']':if(stack.isEmpty()||!stack.pop().equals('['))returnfalse;break;default:returnfalse;}}returnstack.isEmpty();}}
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 →
Simple switch case within a for loop