Super Reduced String

  • + 0 comments

    Easy to read Java with stack

    public static String superReducedString(String s) {
        // Write your code here
            Stack<Character> stack = new Stack(); 
            char[] chars = s.toCharArray(); 
            for(char c: chars){
                if(!stack.isEmpty() && c == stack.peek()){
                    stack.pop();
                }else{
                    stack.push(c);
                }
            }
            
            StringBuilder result = new StringBuilder(); 
            
            while(!stack.isEmpty()){
                result.insert(0,stack.pop());
                System.out.println(result);
            }
            
            if(result.length()==0){
                return "Empty String";
            }
            return result.toString(); 
            
        }