Problem · String
Template Variable Expansion
Learn this problemProblem statement
You are given key-value mappings and a source string. Any substring inside a pair of percent signs, such as %key%, should be treated as a key and replaced by its mapped value.
A mapped value may itself contain another key placeholder, so replacements may need to be resolved recursively.
If a referenced key is missing, or if resolving placeholders finds a cycle, return "ERROR".
Function
expandTemplate(mappings: String[][], source: String) → StringExamples
Example 1
mappings = [["x","%y%/home"],["y","user"]]source = "/%x%/docs"return = "/user/home/docs"%x% expands to %y%/home, and %y% expands to user.
The source shared the rule but did not include this exact sample. FastPrep added this small example so the behavior can be checked directly.