synopsis · Linear patterns · chapter 20
String Parsing & Expression Evaluation
10 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
Parsing = one index walks the text once. Read a whole token (number, word, operator), decide what it means from what came before, move on.
- use it when
"Implement atoi", "evaluate this expression", "encode a list into one string", "justify text", "convert numerals" → a scanner, a few states, maybe a stack.
- template
while (i < n && s.charAt(i) >= '0' && s.charAt(i) <= '9') num = num * 10 + (s.charAt(i++) - '0');— read the whole number. - cost
Each character is read once → O(n). Stacks for brackets or precedence: O(n) space worst case; a recursive parser uses O(depth) call stack.
- trap
Overflow: check
result > (MAX - d) / 10beforeresult * 10 + d. After the multiply it has already wrapped. - trap
Character.isDigit('५')is true. In parsers testc >= '0' && c <= '9', or other scripts' digits slip in andc - '0'is garbage. - pro tip
Precedence with two stacks: before pushing an operator, apply every waiting one with precedence ≥ it. Or write
expr → term → factor. - pro tip
No brackets?
result= finished terms,last= the term*and/can still change. On + or −, banklast. - template
Framing:
sb.append(s.length()).append('#').append(s). The reader jumps by the length, so a#in the data never confuses it. - what it is
Greedy table (Roman, lakh/crore, h:m:s): biggest value that fits, repeat. Greedy lines: take words while they fit, then
spaces / gaps,spaces % gaps.
Shaky on a card? Open the chapter or flip its recall cards.