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
| Shape | Loop | Problem here |
|---|---|---|
| Translate each character | one pass, append a code for each | Mobile keypad sequence |
| Remove by a rule until stable | repeat passes until one removes nothing | Remove adjacent duplicates |
| Count the fewest moves | scan both strings from the end, matching what can stay | Transform 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
- Convert a Sentence into its equivalent mobile numeric keypad sequencemediumguide ready
- Recursively remove all adjacent duplicatesmediumguide ready
- Transform One String to Another using Minimum Number of Given Operationmediumguide ready