Drill

ProblemsJava › patterns

Cancel out the doubled keystrokes

mediumpatternsStacksStringsJava

A faulty keyboard doubles a letter now and then. The cleaner removes any two identical letters sitting next to each other, and keeps going while that leaves a new pair behind.

collapseDoubles(typed: string) → string

Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

String collapseDoubles(String typed) {
    
}

Worked examples

CallResult
collapseDoubles("abbaca")"ca"
collapseDoubles("azxxzy")"ay"
collapseDoubles("abc")"abc"
collapseDoubles("aa")""

Hint

Build the result on a stack. For each character, either it cancels the one on top or it goes on top — no rescanning needed.

Reference solution in Java
String collapseDoubles(String typed) {
    StringBuilder kept = new StringBuilder();
    for (int i = 0; i < typed.length(); i++) {
        char ch = typed.charAt(i);
        int last = kept.length() - 1;
        if (last >= 0 && kept.charAt(last) == ch) kept.deleteCharAt(last);
        else kept.append(ch);
    }
    return kept.toString();
}

The same problem in another language

More patterns problems in Java