Apply Substitutions Problem
Description
LeetCode Problem 3481.
You are given a replacements mapping and a text string that may contain placeholders formatted as %var%, where each var corresponds to a key in the replacements mapping. Each replacement value may itself contain one or more such placeholders. Each placeholder is replaced by the value associated with its corresponding replacement key.
Return the fully substituted text string which does not contain any placeholders.
Example 1:
Input: replacements = [["A","abc"],["B","def"]], text = "%A%_%B%"
Output: "abc_def"
Explanation:
- The mapping associates "A" with "abc" and "B" with "def".
- Replace %A% with "abc" and %B% with "def" in the text.
- The final text becomes "abc_def".
Example 2:
Input: replacements = [["A","bce"],["B","ace"],["C","abc%B%"]], text = "%A%_%B%_%C%"
Output: "bce_ace_abcace"
Explanation:
- The mapping associates "A" with "bce", "B" with "ace", and "C" with "abc%B%".
- Replace %A% with "bce" and %B% with "ace" in the text.
- Then, for %C%, substitute %B% in "abc%B%" with "ace" to obtain "abcace".
- The final text becomes "bce_ace_abcace".
Constraints:
1 <= replacements.length <= 10- Each element of
replacementsis a two-element list[key, value], where:keyis a single uppercase English letter.valueis a non-empty string of at most 8 characters that may contain zero or more placeholders formatted as%<key>%.
- All replacement keys are unique.
- The
textstring is formed by concatenating all key placeholders (formatted as%<key>%) randomly from the replacements mapping, separated by underscores. text.length == 4 * replacements.length - 1- Every placeholder in the
textor in any replacement value corresponds to a key in thereplacementsmapping. - There are no cyclic dependencies between replacement keys.
Solution
Approach: Recursive Expansion with a Hash Map
Store the replacements in a hash map from key to value. Then write a recursive function expand(s) that returns s with every placeholder replaced:
- Find the first
%ins. If there is none, returns. - Find the next
%after it. That pair delimits one placeholder, and the text between them is the key. - Return the text before the placeholder, then
expand(map[key]), thenexpandof everything after the closing%.
Since the replacements have no cyclic dependencies, the recursion always ends.
Complexity: O(L) time and space, where L is the total length of the fully expanded text (with at most 10 keys and values of at most 8 characters it stays small).
class Solution:
def applySubstitutions(self, replacements: List[List[str]], text: str) -> str:
def dfs(s: str) -> str:
i = s.find("%")
if i == -1:
return s
j = s.find("%", i + 1)
if j == -1:
return s
key = s[i + 1 : j]
replacement = dfs(d[key])
return s[:i] + replacement + dfs(s[j + 1 :])
d = {s: t for s, t in replacements}
return dfs(text)