【每日一题Day105】LC2325解密消息 | 哈希表

解密消息【LC2325】

You are given the strings key and message, which represent a cipher key and a secret message, respectively. The steps to decode message are as follows:

  1. Use the first appearance of all 26 lowercase English letters in key as the order of the substitution table.
  2. Align the substitution table with the regular English alphabet.
  3. Each letter in message is then substituted using the table.
  4. Spaces ' ' are transformed to themselves.
  • For example, given key = "**hap**p**y** **bo**y" (actual key would have at least one instance of each letter in the alphabet), we have the partial substitution table of ('h' -> 'a', 'a' -> 'b', 'p' -> 'c', 'y' -> 'd', 'b' -> 'e', 'o' -> 'f').

Return the decoded message.

到学校了,晕高铁地铁真是太惨了
可能要请两天假,滑雪一切顺利~

  • 思路:使用哈希表记录每个字母对应的译文,然后结果为以message中的每个字母为key的value值的拼接

  • 实现

    class Solution {
        public String decodeMessage(String key, String message) {
            Map<Character,Character> map = new HashMap<>();
            map.put(' ',' ');
            int idx = 0;
            for (int i = 0; i < key.length(); i++){
                if (idx == 26) break;
                char c = key.charAt(i);
                if (!map.containsKey(c)){
                    map.put(c, (char)('a' + idx++));
                }
            }
            StringBuilder res = new StringBuilder();
            for (int i = 0; i < message.length(); i++){
                res.append(map.get(message.charAt(i)));
            }
            return res.toString();
    
    
        }
    }
    
    • 复杂度
      • 时间复杂度: O ( n + m ) O(n+m) O(n+m),n、m为字符串长度,
      • 空间复杂度: O ( C ) O(C) O(C),C为字符集大小,本题中为27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值