Problem solution · C++

Apply Substitutions

Apply Substitutions: a C++ solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Depth-first search
Source
walkccc LeetCode Solutions
Length
35 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeApply Substitutions · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  string applySubstitutions(vector<vector<string>>& replacements, string text) {    unordered_map<string, string> replaceMap;     for (const vector<string>& replacement : replacements) {      const string& key = replacement[0];      const string& value = replacement[1];      replaceMap[key] = value;    }     return evaluate(text, replaceMap);  }  private:  // Evaluates the `text` and replaces the placeholders with the values  // from the `replaceMap` recursively.  string evaluate(const string& text,                  const unordered_map<string, string>& replaceMap) {    string res;    int i = 0;    while (i < text.length())      if (text[i] == '%') {        const int j = i + 1 + text.substr(i + 1).find('%');        const string key = text.substr(i + 1, j - i - 1);        const string value = replaceMap.at(key);        res += evaluate(value, replaceMap);        i = j + 1;      } else {        res += text[i++];      }    return res;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗