Super Reduced String

  • + 0 comments

    Java O(n)

    public static String superReducedString(String s) {
            Stack<Character> stack = new Stack<>();
            
            for (char c : s.toCharArray()) {
                if (!stack.isEmpty() && stack.peek() == c) {
                    stack.pop();
                } else {
                    stack.push(c);
                }
            }
            
            StringBuilder sb = new StringBuilder();
            for (char c : stack) {
                sb.append(c);
            }
            
            return sb.length() == 0 ? "Empty String" : sb.toString();
        }