解密消息【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 ),n、m为字符串长度,
- 空间复杂度:O(C),C为字符集大小,本题中为27