【每日一题Day85】LC1807 替换字符串中的括号内容 | 哈希表 双指针

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

替换字符串中的括号内容【LC1807】

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.

不看题目 直接看示例更快

  • 思路:

    • 为了快速替换,使用哈希表存储键值和对应的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为数组的大小
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值