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.
I agree. It is not necessary to iterate over the string multiple times or construct intermediate results. Surprisingly few people tried the stack approach. Here is my solution in Java.
publicstaticvoidmain(String[]args){Scannerscanner=newScanner(System.in);Strings=scanner.next();System.out.println(reduce(s));}privatestaticStringreduce(Strings){Stack<Character>stack=newStack<>();inth=0;//height of stackfor(inti=0;i<s.length();i++){if(!stack.isEmpty()&&stack.peek().equals(s.charAt(i))){stack.pop();//throw awayh--;}else{stack.push(s.charAt(i));h++;}}if(h==0){return"Empty String";}//at the end, stack holds reduced string in reverse order.char[]reduced=newchar[h];for(inti=h-1;i>=0;i--){reduced[i]=stack.pop();}returnnewString(reduced);}
Super Reduced String
You are viewing a single comment's thread. Return to all comments →
I agree. It is not necessary to iterate over the string multiple times or construct intermediate results. Surprisingly few people tried the stack approach. Here is my solution in Java.