Evaluate the Bracket Pairs of a String LeetCode solution in C++

1
class Solution {
2
public:
3
string evaluate(string s, vector<vector<string>> &knowledge) {
4
string ans; // resultant string
5
int n = s.size();
6
if (n < 2) return s; // because () will come in pair so, size should be more than 2
7
int sz = knowledge.size();
8
unordered_map<string, string> mp; // To reduce Runtime otherwise it will give TLE
9
for (int i = 0; i < sz; ++i) {
10
mp.insert({knowledge[i][0], knowledge[i][1]}); // Inserting {key, value} pair
11
}
12
for (int i = 0; i < n; i++) {
13
if (s[i] == '(') {
14
string key;
15
i++;
16
while (s[i] != ')') { // getting key till we get ')'
17
key += s[i++];
18
}
19
string value;
20
if (mp.find(key) != mp.end()) { // If {key, value} pair is present then
21
// replace (key) by it's value
22
value = mp[key];
23
ans += value;
24
} else { // otherwise replace (key) by ?
25
ans += "?";
26
}
27
} else
28
ans += s[i];
29
}
30
return ans;
31
}
32
};
33

34
**Please do upvote **

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0