Skip to main content
Back to problems
#1807
Medium Algorithms

Evaluate the bracket pairs of a string

Array Hash Table String
69.3% acceptance
Feb 25, 2026
517
43
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.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
use std::collections::HashMap;


impl Solution {
  pub fn evaluate(s: String, knowledge: Vec<Vec<String>>) -> String {
    let map: HashMap<&str, &str> = knowledge.iter()
      .map(|kv| (kv[0].as_str(), kv[1].as_str()))
      .collect();
    
    let mut result = String::new();
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
      if c == '(' {
        let mut key = String::new();
        for kc in chars.by_ref() {
          if kc == ')' { break; }
          key.push(kc);
        }
        if let Some(&val) = map.get(key.as_str()) {
          result.push_str(val);
        } else {
          result.push('?');
        }
      } else {
        result.push(c);
      }
    }
    result
  }
}