Logger Pattern Formatter
Difficulty: Hard · Topics: State Machine, Parsing, Formatting · Acceptance: 100.0% of 1 submissions
Difficulty: Hard | Tags: Parsing, State Machine, Formatting
Description
Implement a pattern-based message formatter (similar to Java's MessageFormat). The pattern contains literal text mixed with placeholders in the form {index} or {index, type} or {index, type, style}.
Placeholder syntax: {argumentIndex [, formatType [, formatStyle]]}
Implement:
applyPattern(pattern) → parsed format object
format(pattern, args...) → String
Examples
Example 1 — Simple:
Input:
pattern = "Hello, {0}! You have {1} messages."
args = ["Alice", 5]
Output: "Hello, Alice! You have 5 messages."
Example 2 — Typed:
Input:
pattern = "Date: {0, date}. Amount: {1, number, currency}"
args = [Date(2026-02-19), 1234.56]
Output: "Date: Feb 19, 2026. Amount: $1,234.56"
Example 3 — Escaped braces:
Input:
pattern = "Use '{'curly braces'}' like this: {0}"
args = ["test"]
Output: "Use {curly braces} like this: test"
Example 4 — Invalid pattern:
Input: pattern = "Hello, {0"
Output: Error — "Unmatched braces in the pattern."
Supported Format Types
| Type | Styles |
|---|---|
number | default, currency, percent, integer, custom pattern |
date | short, medium, long, full, custom SimpleDateFormat |
time | short, medium, long, full, custom SimpleDateFormat |
choice | ChoiceFormat pattern |
Constraints
- Argument index must be a non-negative integer.
- Single quotes
'escape literal text;''produces a literal'. - Nested braces inside format styles are tracked with a brace counter.
- Pattern length ≤ 10^4.
Hints
Hint 1
Build a state machine with segments: RAW, INDEX, TYPE, MODIFIER. Switch states on encountering {, }, and ,.
---
## Algorithms