替换字符串中的括号内容【LC1807】
You are given a string
sthat 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
knowledgewhere eachknowledge[i] = [keyi, valuei]indicates that keykeyihas a value ofvaluei.You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key
keyi, you will:
- Replace
keyiand the bracket pair with the key’s correspondingvaluei.- If you do not know the value of the key, you will replace
keyiand 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 ins.Return the resulting string after evaluating all of the bracket pairs.
不看题目 直接看示例更快
-
思路:
- 为了快速替换,使用哈希表存储键值和对应的value值。
- 如果当前字符不是左括号,那么将其直接放入结果末尾;如果是左括号,那么搜索括号内的单词,然后进行替换。
- 替换规则为:如果哈希表内存在该单词,则替换为value值,不存在则替换为"?"
-
思路
class Solution { public String evaluate(String s, List<List<String>> knowledge) { int n = s.length(); Map<String,String> map = new HashMap<>(); for (List<String> list : knowledge){ map.put(list.get(0), list.get(1)); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++){ if (s.charAt(i) != '('){ sb.append(s.charAt(i)); }else{ int j = i + 1; while(s.charAt(j) != ')'){ j++; } sb.append(map.getOrDefault(s.substring(i + 1, j), "?")); i = j; } } return sb.toString(); } }- 复杂度
- 时间复杂度:O(n)O(n)O(n),n为字符串长度
- 空间复杂度:O(m)O(m)O(m),m为数组的大小
- 复杂度

给定一个包含括号对的字符串,每对括号内有一个非空键。使用一个键值对的知识库,将所有括号对中的键替换为对应的值。如果键在知识库中找不到,替换为问号。实现一个解决方案,使用哈希表存储键值对,遍历字符串进行替换。时间复杂度和空间复杂度均为线性。

被折叠的 条评论
为什么被折叠?



