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 evaluatingall of the bracket pairs.
Input: s ="(name)is(age)yearsold", knowledge =[["name","bob"],["age","two"]]Output: "bobistwoyearsold"Explanation:
The key "name" has a value of "bob", so replace "(name)"with"bob".The key "age" has a value of "two", so replace "(age)"with"two".
Input: s ="(a)(a)(a)aaa", knowledge =[["a","yes"]]Output: "yesyesyesaaa"Explanation: The same key can appear multiple times.The key "a" has a value of "yes", so replace all occurrences of "(a)"with"yes".Notice that the "a"s not in a bracket pair are not evaluated.
We can use a hash map to store the key-value pairs from knowledge. As we scan the string, whenever we find a bracket pair, we extract the key and replace it with its value from the map (or ? if not found).
classSolution {
funevaluate(s: String, knowledge: List<List<String>>): String {
val mp = knowledge.associate { it[0] to it[1] }
val ans = StringBuilder()
var inBracket = falseval key = StringBuilder()
for (c in s) {
when {
c =='('-> {
inBracket = true key.clear()
}
c ==')'-> {
ans.append(mp[key.toString()] ?:"?")
inBracket = false }
inBracket -> key.append(c)
else-> ans.append(c)
}
}
return ans.toString()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
defevaluate(self, s: str, knowledge: list[list[str]]) -> str:
mp = {k: v for k, v in knowledge}
ans = []
i =0 n = len(s)
while i < n:
if s[i] =='(':
j = i +1while s[j] !=')':
j +=1 key = s[i+1:j]
ans.append(mp.get(key, '?'))
i = j +1else:
ans.append(s[i])
i +=1return''.join(ans)