Leetcode 1807: Evaluate the Bracket Pairs of a String

grid47
grid47
Exploring patterns and algorithms
May 10, 2024 7 min read

You are given a string s containing several bracket pairs with non-empty keys. You are also provided a 2D array knowledge where each element is a key-value pair. Your task is to evaluate the string by replacing the keys inside the bracket pairs with their corresponding values. If a key is unknown, replace it with a question mark ?.
Problem
Approach
Steps
Complexity
Input: The input consists of a string `s` and a 2D array `knowledge` containing key-value pairs.
Example: s = "(user)likes(cats)", knowledge = [["user","Alice"], ["cats","dogs"]]
Constraints:
• 1 <= s.length <= 10^5
• 0 <= knowledge.length <= 10^5
• knowledge[i].length == 2
• 1 <= keyi.length, valuei.length <= 10
• The string `s` contains lowercase English letters and round brackets `(` and `)`.
Output: Return the resulting string after evaluating all the bracket pairs in `s`.
Example: Output: "Alicelikesdogs"
Constraints:
• The output should be a string where each key in a bracket pair is replaced by its corresponding value or `?` if unknown.
Goal: To evaluate all bracket pairs in the string and replace keys with their corresponding values or `?` if unknown.
Steps:
• Initialize a map to store the key-value pairs from `knowledge`.
• Iterate over the string `s` and whenever a bracket pair is encountered, extract the key.
• Check if the key is in the map, and replace it with its corresponding value or `?` if not found.
• Continue processing the string and append the modified parts to the result string.
Goal: The string `s` is at most 100,000 characters long and contains bracket pairs. The array `knowledge` contains unique key-value pairs.
Steps:
• The solution should handle both small and large inputs efficiently.
• The output string should be constructed with respect to the input size constraints.
Assumptions:
• The input string `s` will always contain valid bracket pairs.
• All keys in `knowledge` are unique.
Input: s = "(user)likes(cats)", knowledge = [["user","Alice"], ["cats","dogs"]]
Explanation: The key "user" has a value of "Alice" and "cats" has a value of "dogs", so the final output is "Alicelikesdogs".

Input: s = "hello(name)", knowledge = [["name","Bob"]]
Explanation: The key "name" has a value of "Bob", so replace the bracket pair with the value and the result is "hellobob".

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus