Approach
Depth-first search
For Apply Substitutions, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 35 lines of C++ from the credited upstream file 3481.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 2 loop blocks detected.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 string applySubstitutions(vector<vector<string>>& replacements, string text) {4 unordered_map<string, string> replaceMap;5 6 for (const vector<string>& replacement : replacements) {7 const string& key = replacement[0];8 const string& value = replacement[1];9 replaceMap[key] = value;10 }11 12 return evaluate(text, replaceMap);13 }14 15 private:16 17 18 string evaluate(const string& text,19 const unordered_map<string, string>& replaceMap) {20 string res;21 int i = 0;22 while (i < text.length())23 if (text[i] == '%') {24 const int j = i + 1 + text.substr(i + 1).find('%');25 const string key = text.substr(i + 1, j - i - 1);26 const string value = replaceMap.at(key);27 res += evaluate(value, replaceMap);28 i = j + 1;29 } else {30 res += text[i++];31 }32 return res;33 }34};35