Learn / Strings

String building

Some problems build a new string piece by piece: translate each character, drop some characters, or rebuild after a change. Collect the pieces in a builder and join once. When the rule must be applied until nothing changes, loop until a pass makes no change.

How to recognise it

  • Each character turns into some output text (a code, a key sequence, a number).
  • Characters are removed by a rule, and removing some can create new cases to remove.
  • The question asks for the fewest moves to turn one string into another under a fixed kind of move.

The idea in one picture

Think of an assembly line. Each character of the input arrives, a rule decides what (if anything) to put in the output box, and at the end the box is sealed into one string. When the rule can create new work, the whole box goes round the line again.

Three shapes

ShapeLoopProblem here
Translate each characterone pass, append a code for eachMobile keypad sequence
Remove by a rule until stablerepeat passes until one removes nothingRemove adjacent duplicates
Count the fewest movesscan both strings from the end, matching what can stayTransform one string to another

Template: repeat until nothing changes

loop:
    next = empty builder
    for each run of equal characters in s:
        if the run has length 1: append it to next
    if next has the same length as s: return s
    s = next

Common mistakes

  • Removing pairs only, when the rule says a whole run of equal characters goes.
  • Stopping after one pass when removals can create new runs.
  • Appending to an immutable string in a loop (Java +), which is O(n²).
  • Forgetting to check first that a transformation is possible at all (the two strings must have the same letters).

Problems

0 of 3 solved

Check yourself

In "remove all adjacent duplicates recursively", why must you repeat the pass?

The only move takes a character from A and puts it at the front. Which characters never need to move?

Why use a lookup table for the phone keypad codes?