LeetCode 1807: Evaluate the Bracket Pairs of a String
LeetCode 1807 Solution Explanation
Explanation:
We can solve this problem using a HashMap to store the key-value pairs from the knowledge array. Then, we can iterate through the string and whenever we encounter a bracket pair, we can check if the key exists in our HashMap. If it does, we replace the bracket pair with the corresponding value; otherwise, we replace it with a question mark.
Algorithm:
- Create a HashMap to store the key-value pairs from the knowledge array.
- Iterate through the string:
- If an opening bracket is found, extract the key until the closing bracket.
- Check if the key exists in the HashMap.
- Replace the bracket pair with the corresponding value or a question mark.
- Return the modified string.
Time Complexity:
The time complexity of this solution is O(n), where n is the length of the input string.
Space Complexity:
The space complexity is O(k), where k is the number of unique keys in the knowledge array.
:
LeetCode 1807 Solutions in Java, C++, Python
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 sb = new StringBuilder();
int n = s.length();
int i = 0;
while (i < n) {
char c = s.charAt(i);
if (c == '(') {
int j = i + 1;
while (s.charAt(j) != ')') {
j++;
}
String key = s.substring(i + 1, j);
sb.append(map.getOrDefault(key, "?"));
i = j + 1;
} else {
sb.append(c);
i++;
}
}
return sb.toString();
}
}
Interactive Code Editor for LeetCode 1807
Improve Your LeetCode 1807 Solution
Use the editor below to refine the provided solution for LeetCode 1807. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...