/**
* Problem: LeetCode 1807 - Evaluate the Bracket Pairs of a String
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
import java.util.*;
/**
* Problem: LeetCode 1807 - Evaluate the Bracket Pairs of a String
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public String evaluate(String s, List<List<String>> knowledge) {
Map<String, String> map = new HashMap<>();
for (List<String> pair : knowledge) {
map.put(pair.get(0), pair.get(1));
}
StringBuilder result = new StringBuilder();
int i = 0;
int n = s.length();
while (i < n) {
if (s.charAt(i) == '(') {
int j = i + 1;
while (s.charAt(j) != ')') {
j++;
}
String key = s.substring(i + 1, j);
result.append(map.getOrDefault(key, "?"));
i = j + 1;
} else {
result.append(s.charAt(i));
i++;
}
}
return result.toString();
}
}
"""
Problem: LeetCode 1807 - Evaluate the Bracket Pairs of a String
Difficulty: Medium
Language: Python
Author: CodeByTushu
"""
from typing import List
class Solution:
def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
d = {k: v for k, v in knowledge}
result = []
i = 0
n = len(s)
while i < n:
if s[i] == '(':
j = i + 1
while s[j] != ')':
j += 1
key = s[i + 1:j]
result.append(d.get(key, '?'))
i = j + 1
else:
result.append(s[i])
i += 1
return "".join(result)
/**
* Problem: LeetCode 1807 - Evaluate the Bracket Pairs of a String
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;
/**
* Problem: LeetCode 1807 - Evaluate the Bracket Pairs of a String
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
class Solution {
public:
string evaluate(string s, vector<vector<string>>& knowledge) {
unordered_map<string, string> dict;
for (const auto& pair : knowledge) {
dict[pair[0]] = pair[1];
}
string result = "";
result.reserve(s.size());
int i = 0;
int n = s.size();
while (i < n) {
if (s[i] == '(') {
int j = i + 1;
while (s[j] != ')') {
j++;
}
string key = s.substr(i + 1, j - i - 1);
auto it = dict.find(key);
if (it != dict.end()) {
result += it->second;
} else {
result += '?';
}
i = j + 1;
} else {
result += s[i];
i++;
}
}
return result;
}
};
/**
* Problem: LeetCode 1807 - Evaluate the Bracket Pairs of a String
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
var evaluate = function(s, knowledge) {
const map = new Map();
for (const [k, v] of knowledge) {
map.set(k, v);
}
const result = [];
let i = 0;
const n = s.length;
while (i < n) {
if (s[i] === '(') {
let j = i + 1;
while (s[j] !== ')') {
j++;
}
const key = s.slice(i + 1, j);
result.push(map.has(key) ? map.get(key) : '?');
i = j + 1;
} else {
result.push(s[i]);
i++;
}
}
return result.join('');
};