-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3481_Apply-Substitutions.cpp
More file actions
38 lines (37 loc) · 1.21 KB
/
3481_Apply-Substitutions.cpp
File metadata and controls
38 lines (37 loc) · 1.21 KB
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
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public:
string replaceWithKey(string& val, unordered_map<string,string>& wordMap){
if(val.find('%') == string::npos) return val;
string output;
int n = val.size(), idx = 0;
while(idx < n){
if(val[idx] == '%'){
string temp;
++idx;
while(idx < n && val[idx] != '%'){
temp.push_back(val[idx]);
++idx;
}
if(!wordMap.count(temp)) return "";
output.append(wordMap[temp]);
}else{
output.push_back(val[idx]);
}
++idx;
}
return output;
}
string applySubstitutions(vector<vector<string>>& replacements, string text) {
unordered_map<string, string> wordMap;
queue<pair<string,string>> q;
for(auto& p : replacements) q.push({p[0], p[1]});
while(!q.empty()){
auto& [key, val] = q.front();
string resolved = replaceWithKey(val, wordMap);
if(resolved.empty()) q.push({key, val});
else wordMap[key] = resolved;
q.pop();
}
return replaceWithKey(text, wordMap);
}
};