# step 0: create the replacement dict, let the key search time complexity from O(n) to O(1) # step 1: walk the text, if text[i] == '%', we replace %{text[i + 1]}% with replacement dict[text[i + 1]] # step 2: if '%' in replacement dict[text[i + 1]], we let replacement dict[text[i + 1]] as new text, do step 1 and 2
# the size of replacements: # the size of text: t # time complexity: O(r^2 * t) # space comlexity: O(r^2 * t)
replaceDict = {} for k, v in replacements: replaceDict[k] = v
defparse(text):
result = [] i = 0 while i < len(text):
if text[i] != '%': result.append(text[i]) i += 1 else: if'%'in replaceDict[text[i + 1]]: replaceDict[text[i + 1]] = parse(replaceDict[text[i + 1]])
result.append(replaceDict[text[i + 1]]) i += 3
return''.join(result)
return parse(text)
# step 0: we walk the replacements # step 1: check every replacement is in text or not # if replacement in text: text = text.replace(replacement[0], replacement[1]) # need_rerun = need_rerun or '%' in replacement[1] # step 2: run until need_rerun is False # step 3: return text
# rerun time: R # the size of replacements: r # the size of text: t # time complexity: O(r^2 * t)
# space complexity: O(t^2 * t)
need_run = True
skip = set()
while need_run: need_run = False
for replace, replace_with in replacements: if replace in skip: continue
if (target := f'%{replace}%') in text: text = text.replace(target, replace_with)