String parsing
Parsing means reading a string by its own rules: symbols with values, words split by spaces, runs of equal digits. Walk the string with an index, look ahead one character when the rule needs it, and build the answer as you go.
How to recognise it
- The input follows a format (Roman numerals, words with extra spaces, a described sequence).
- The meaning of a character depends on its neighbour (as in IV versus VI).
- The output is produced by reading runs or tokens one at a time.
The idea in one picture
Read the string the way you would read it aloud: one token at a time, sometimes glancing at the next symbol before deciding what the current one means.
Three shapes
| Shape | Loop | Problem here |
|---|---|---|
| One symbol, peek at the next | for i, compare value(s[i]) with value(s[i + 1]) | Roman to Integer |
| Tokens split by spaces | skip spaces, then read a word | Reverse Words in a String |
| Runs of equal characters | j walks to the end of a run starting at i | Count and Say |
Template: walking runs
i = 0
while i < n:
j = i
while j < n and s[j] == s[i]: j = j + 1
the run is s[i .. j - 1], of length j - i
i = j
The same "skip, then read" loop splits words: skip spaces, then read up to the next space.
Common mistakes
- Looking ahead past the end of the string.
- Splitting on a single space, which leaves empty words when spaces repeat.
- Building the next term while still reading the current one, in the same variable.
Problems
- Roman to Integereasyguide ready
- Reverse Words in a Stringmediumguide ready
- Count and Saymediumguide ready