A template contains tokens wrapped in braces, like {name}. Given a map of token names to
values, return the template with every token replaced by its value. A token with no rule
is left untouched (braces and all).
tokenReplace(template, rules)
Input format: template | rules, rules as space-separated name=value entries.
"hi {name}", rules name=sam // → "hi sam"
"{a}-{b}", rules a=1 b=2 // → "1-2"
"{x} stays", (no rule for x) // → "{x} stays"
This is text-scanning: walk the template character by character, recognizing a special syntax (braces) and passing everything else through unchanged. "Most characters get copied, but a specific marker triggers special handling" is common to a wide range of parsing tasks.
Walk with a position pointer, building output as you go. At each position:
Check if the name exists in the rules. If yes, replace the entire {name} span with the rule's value. If no, the problem specifies leaving it completely untouched — copy the literal {name} through, not dropping it or erroring.
Either way, advance the pointer past the closing brace, resuming the scan right after the token.
An opening brace with no matching closing brace anywhere after it means no complete token to extract — treat that brace as an ordinary literal character and continue scanning normally.
Since tokens don't nest or overlap here (that's reserved for token-transform), you never look backward — each character or token resolves the moment you encounter it, with steady forward progress.
Each character is visited a constant number of times — O(n) time, O(n) space for the output.
def token_replace(template, rules):
out = []
i = 0
while i < len(template):
if template[i] == "{":
end = template.find("}", i)
if end != -1:
name = template[i + 1:end]
if name in rules:
out.append(rules[name])
else:
out.append(template[i:end + 1])
i = end + 1
continue
out.append(template[i])
i += 1
return "".join(out)
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.