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

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

解密消息【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
阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

“【每日一题Day105】LC2325解密消息 | 哈希表” 的相关文章