[LeetCode] Evaluate the Bracket Pairs of a String

1807. Evaluate the Bracket Pairs of a String

You are given a string s that contains some bracket pairs, with each pair containing a non-empty key.

  • For example, in the string “(name)is(age)yearsold”, there are two bracket pairs that contain the keys “name” and “age”.

You know the values of a wide range of keys. This is represented by a 2D string array knowledge where each knowledge[i] = [keyi, valuei] indicates that key keyi has a value of valuei.

You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key keyi, you will:

  • Replace keyi and the bracket pair with the key’s corresponding valuei.
  • If you do not know the value of the key, you will replace keyi and the bracket pair with a question mark “?” (without the quotation marks).

Each key will appear at most once in your knowledge. There will not be any nested brackets in s.

Return the resulting string after evaluating all of the bracket pairs.

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
class Solution {
public:
string evaluate(string s, vector<vector<string>>& knowledge) {
stringstream ss;
string key = "";
unordered_map<string, string> m;
bool flag = false;
for(auto p : knowledge) {
m[p[0]] = p[1];
}
for(int i = 0; i < s.length(); i++) {
if(flag) {
if(s[i] == ')') {
if(m.count(key)) {
ss << m[key];
} else {
ss << '?';
}
flag = false;
key = "";
} else {
key += s[i];
}
} else {
if(s[i] == '(') {
flag = true;
} else {
ss << s[i];
}
}
}
return ss.str();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/28/PS/LeetCode/evaluate-the-bracket-pairs-of-a-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.