解密消息【LC2325】
You are given the strings
keyandmessage, which represent a cipher key and a secret message, respectively. The steps to decodemessageare as follows:
- Use the first appearance of all 26 lowercase English letters in
keyas the order of the substitution table.- Align the substitution table with the regular English alphabet.
- Each letter in
messageis then substituted using the table.- 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
- 复杂度

给定一个cipherkey和一个secretmessage,文章描述了解密message的步骤,包括建立替换表并使用该表对message中的每个字母进行替换。提供的Java代码示例展示了如何构建哈希映射并解码message。
6719

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



