2325.解密消息
链接:2325.解密消息
难度:Easy
标签:哈希表、字符串
简介:返回解密后的消息。
题解 1 - cpp
- 编辑时间:2023-02-01
- 执行用时:24ms
- 内存消耗:15.9MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
public:
string decodeMessage(string key, string message) {
char list[26] = {0};
for (int i = 0, p = 'a'; i < key.size(); i++) {
if (key[i] != ' ' && list[key[i] - 'a'] == 0) list[key[i] - 'a'] = p++;
}
string ans = "";
for (auto &c : message) {
if (c == ' ') ans += " ";
else ans += list[c - 'a'];
}
return ans;
}
};
题解 2 - python
- 编辑 时间:2023-02-01
- 执行用时:48ms
- 内存消耗:15.1MB
- 编程语言:python
- 解法介绍:同上。
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
list = [''] * 26
p = 'a'
for c in key:
i = ord(c) - ord('a')
if c != ' ' and list[i] == '':
list[i] = p
p = chr(ord(p) + 1)
ans = ''
for c in message:
if c == ' ':
ans += ' '
else:
ans += list[ord(c) - ord('a')]
return ans
题解 3 - rust
- 编辑时间:2023-02-01
- 内存消耗:2.1MB
- 编程语言:rust
- 解法介绍:同上。
impl Solution {
pub fn decode_message(key: String, message: String) -> String {
let message = message.chars().collect::<Vec<char>>();
let key = key.chars().collect::<Vec<char>>();
let mut list = ['\0'; 26];
let mut ans = String::new();
let mut p = 'a';
for c in key {
let i = c as usize - 'a' as usize;
if c != ' ' && list[i] == '\0' {
list[i] = p;
p = (p as u8 + 1) as char;
}
}
for c in message {
if c == ' ' {
ans.push(' ');
} else {
ans.push(list[c as usize - 'a' as usize]);
}
}
ans
}
}