Leetcode.2325 解密消息
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
题目链接
Leetcode.2325 解密消息 Rating 1268
题目描述
给你字符串 key
和 message
分别表示一个加密密钥和一段加密消息。解密 message
的步骤如下
使用 key
中 26 个英文小写字母第一次出现的顺序作为替换表中的字母 顺序 。
将替换表与普通英文字母表对齐形成对照表。
按照对照表 替换 message
中的每个字母。
空格 ’ ’ 保持不变。
例如key = "happy boy"
实际的加密密钥会包含字母表中每个字母 至少一次据此可以得到部分对照表'h' -> 'a'、'a' -> 'b'、'p' -> 'c'、'y' -> 'd'、'b' -> 'e'、'o' -> 'f'
。
返回解密后的消息。
示例 1
输入key = “the quick brown fox jumps over the lazy dog”, message = “vkbs bs t suepuv”
输出“this is a secret”
解释对照表如上图所示。
提取 “the quick brown fox jumps over the lazy dog” 中每个字母的首次出现可以得到替换表。
示例 2
输入key = “eljuxhpwnyrdgtqkviszcfmabo”, message = “zwx hnfx lqantp mnoeius ycgk vcnjrdb”
输出“the five boxing wizards jump quickly”
解释对照表如上图所示。
提取 “eljuxhpwnyrdgtqkviszcfmabo” 中每个字母的首次出现可以得到替换表。
提示
- 26 < = k e y . l e n g t h < = 2000 26 <= key.length <= 2000 26<=key.length<=2000
key
由小写英文字母及' '
组成key
包含英文字母表中每个字符'a'
到'z'
至少一次- 1 < = m e s s a g e . l e n g t h < = 2000 1 <= message.length <= 2000 1<=message.length<=2000
message
由小写英文字母和' '
组成
分析
只需要把 key
中的字母按照先后顺序映射到 'a','b','c',...,'z'
最后的 message
再按照这个映射得到其替换表即可。
时间复杂度 O ( n ) O(n) O(n)
C++代码
class Solution {
public:
string decodeMessage(string key, string message) {
unordered_map<char,char> umap;
char ch = 'a';
for(auto c:key){
if(c == ' ') continue;
else{
//只记录第一次出现的字母 后面再遇到相同的就不管
if(umap.count(c)) continue;
else{
umap[c] = ch++;
}
}
}
for(auto &c:message){
if(c != ' ') c = umap[c];
}
return message;
}
};
Java代码
class Solution {
public String decodeMessage(String key, String message) {
Map<Character,Character> map = new HashMap<>();
char ch = 'a';
for(char c:key.toCharArray()){
if(c == ' ') continue;
else{
//只记录第一次出现的字母 后面再遇到相同的就不管
if(map.containsKey(c)) continue;
else{
map.put(c,ch);
ch++;
}
}
}
StringBuilder sb = new StringBuilder();
for(char c:message.toCharArray()){
if(c != ' '){
c = map.get(c);
}
sb.append(c);
}
return sb.toString();
}
}