替换字符串中的括号内容
难度:
标签:
题目描述
代码结果
运行时间: 85 ms, 内存: 49.2 MB
/*
* Solution using Java Streams
*
* This approach is similar to the previous one but utilizes Java Streams and a more functional style.
* We first create a map from the knowledge array. Then we split the string by the parentheses and process the parts accordingly.
*/
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class SolutionStream {
public String evaluate(String s, String[][] knowledge) {
// Create a map from the knowledge array
Map<String, String> map = new HashMap<>();
for (String[] pair : knowledge) {
map.put(pair[0], pair[1]);
}
// Split the string by parentheses and process the parts
return Stream.of(s.split("\\(([^)]+)\\)", -1))
.map(part -> map.getOrDefault(part, part))
.collect(Collectors.joining());
}
}
解释
方法:
该题解采用了 hash map 和线性扫描的方法来解决问题。首先,使用一个字典(knowledge_dict)来存储知识库中的键值对,以便快速查找。接着,通过遍历字符串s,每当遇到'('时,就开始搜索对应的')',提取括号内的字符串作为键,并查询字典中是否有对应的值。如果有,就将这个值添加到结果列表中;如果没有,就添加一个'?'。这个过程中,非括号内容直接添加到结果列表。最后,使用join方法将列表中的内容合并成一个字符串,这就是最终的结果。
时间复杂度:
O(N)
空间复杂度:
O(N)
代码细节讲解
🦆
在处理字符串时,如何确保找到正确的 ')' 来匹配每一个 '('?
▷🦆
如果字符串中存在嵌套的括号,比如 '(name(is(age)))',当前的算法处理方式是否有效?
▷🦆
为什么选择使用列表来存储最终结果,而不是直接在字符串上进行修改?
▷