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.
Use a Stack so that we can solve this problem by traversing the String just once!
Runtime: O(n)
Space Complexity: O(n)
importjava.util.Scanner;importjava.util.Stack;publicclassSolution{publicstaticvoidmain(String[]args){/* Read and save input */Scannerscan=newScanner(System.in);Stringstr=scan.next();scan.close();/* Iterate through String, creating final result in a Stack */Stack<Character>stack=newStack<>();for(inti=0;i<str.length();i++){Characterch=str.charAt(i);if(!stack.isEmpty()&&ch==stack.peek()){stack.pop();}else{stack.push(ch);}}/* Print final result */if(stack.isEmpty()){System.out.println("Empty String");}else{for(charch:stack){System.out.print(ch);}}}}
Let me know if you have any questions.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Super Reduced String
You are viewing a single comment's thread. Return to all comments →
Java solution - passes 100% of test cases
From my HackerRank solutions.
Use a Stack so that we can solve this problem by traversing the String just once!
Runtime: O(n)
Space Complexity: O(n)
Let me know if you have any questions.