[LeetCode] Apply Substitutions

3481. Apply Substitutions

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
string getKey(string& k, unordered_map<string,string>& mp, unordered_map<string,string>& dp) {
if(dp.count(k)) return dp[k];
if(!mp.count(k)) return k;
return dp[k] = process(mp[k], mp, dp);

}
string process(string& s, unordered_map<string,string>& mp, unordered_map<string,string>& dp) {
string res = "", chk = "";
for(auto& ch : s) {
if(ch == '%' or chk != "") {
chk.push_back(ch);
if(chk.size() > 1 and chk.back() == '%') {
res += getKey(chk,mp,dp);
chk = "";
}
} else res.push_back(ch);
}
return res;
}
public:
string applySubstitutions(vector<vector<string>>& replacements, string text) {
unordered_map<string,string> mp, dp;
for(auto& r : replacements) mp["%" + r[0] + "%"] = r[1];
return process(text, mp, dp);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/11/22/PS/LeetCode/apply-substitutions/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.