Evaluate the Bracket Pairs of a String Problem
Description
LeetCode Problem 1807.
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] = [key_i, value_i] indicates that key key_i has a value of value_i.
You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key key_i, you will:
- Replace
key_iand the bracket pair with the key's correspondingvalue_i. - If you do not know the value of the key, you will replace
key_iand 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.
Example 1:
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".
Example 2:
Input: s = "hi(name)", knowledge = [["a","b"]]
Output: "hi?"
Explanation: As you do not know the value of the key "name", replace "(name)" with "?".
Example 3:
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.
Constraints:
1 <= s.length <= 10^50 <= knowledge.length <= 10^5knowledge[i].length == 21 <= key_i.length, value_i.length <= 10sconsists of lowercase English letters and round brackets'('and')'.- Every open bracket
'('inswill have a corresponding close bracket')'. - The key in each bracket pair of
swill be non-empty. - There will not be any nested bracket pairs in
s. key_iandvalue_iconsist of lowercase English letters.- Each
key_iinknowledgeis unique.
Solution
Approach: Hash Map and Scan
Put every pair of knowledge into a hash map from key to value.
Then scan s from left to right. A normal character is copied to the answer. When we meet (, we find the matching ) (brackets never nest), take the key between them, and append the mapped value, or ? if the key is unknown. Then continue after the ).
Complexity: O(n + L) time and O(L) extra space, where n is the length of s and L is the total length of the strings in knowledge.
class Solution:
def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
d = {a: b for a, b in knowledge}
i, n = 0, len(s)
ans = []
while i < n:
if s[i] == '(':
j = s.find(')', i + 1)
ans.append(d.get(s[i + 1 : j], '?'))
i = j
else:
ans.append(s[i])
i += 1
return ''.join(ans)