KatInterview

Fill In Percent-Delimited Tokens From a Lookup Table

StringsAuto-graded · 22 test cases
EasyAuto-gradedStringsstringsparsinghash-map

Last updated

Scan a string left to right, replacing each %key% token with its mapped value and returning None when a key is missing; tests careful linear string parsing.

Fill In Percent-Delimited Tokens From a Lookup Table

You are given a template string template and a dictionary values that maps string keys to string replacement values. Build and return the string obtained by expanding every token in the template.

Tokens

The % character is a delimiter. Each token begins with one % and ends at the next % after it. The characters strictly between those two delimiters form the key (for example, the token %city% has key city).

Rules

  • Read template from left to right.
  • Characters that are not part of a token are copied to the output unchanged.
  • For each token, look up its key in values:
    • If the key is present, write the mapped value to the output in place of the whole token, including both % characters.
    • If the key is absent, the whole function returns None.
  • Replacement values are inserted exactly as given. They are not scanned again for further tokens.
  • Every % in template takes part in exactly one token, so the % characters always come in matched pairs. There is no escape syntax.
  • Two tokens may sit directly next to each other, as in %a%%b%, which holds the tokens %a% and %b%.
  • A template with no % characters is returned unchanged.

Task

Implement expand_tokens(template, values) that returns the expanded string, or None if any token's key is missing from values.

The solution should run in time linear in the length of the template plus the size of the output, not counting dictionary lookups.

Constraints

  • template is a string, possibly empty.
  • The number of % characters in template is even.
  • values is a dictionary from strings to strings; it may be empty.
  • A key between two % characters may be an empty string (%%); it is looked up like any other key.
  • Return type is str on success, or None on failure.

Examples

Example 1

Input: expand_tokens('a%sd%fasd%dog%sdfisan', {'sd': 'HELLO', 'dog': 'CAT'})

Output: 'aHELLOfasdCATsdfisan'

Example 2

Input: expand_tokens('hello %name%!', {'name': 'world'})

Output: 'hello world!'

Example 3

Input: expand_tokens('%a%%b%', {'a': 'x', 'b': 'y'})

Output: 'xy'

Example 4

Input: expand_tokens('plain text', {'unused': 'value'})

Output: 'plain text'

Hints

Hint 1

Walk through the string with an index. Either you are on ordinary text or you are on a `%` that opens a token.

Hint 2

When you see an opening `%`, find the next `%` after it. Everything in between is the key to look up.

Hint 3

After handling a token, resume scanning just past its closing `%`. Collect pieces in a list and join once at the end to stay linear, and return `None` immediately on a missing key.