题目:
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:
Use the first appearance of all 26 lowercase English letters in key as the order of the substitution table.
Align the substitution table with the regular English alphabet.
Each letter in message is then substituted using the table.
Spaces ' ' are transformed to themselves.
For example, given key = "happy boy" (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').
示例:
分析:
容易想到使用哈希表存储密码表,我们将算法分为俩部分,第一部分是创建密码表,第二部是根据密码表得出对应的答案。
首先顺序读取key中的字符,如果字符为空格那么就跳过,如果不是则先判断哈希表关键字中是否已经有该字母,如果没有则按26个字母的顺序将关键字与value一一对应。
其次根据message按照对照表读取得出密文,注意message中的空格需要映射到最终答案中。
流程图:
代码:
//c++
class Solution {
public:
string decodeMessage(string key, string message) {
int n=key.length();
int m=message.length();
int count=0;
string s;
unordered_map<char,char>hashtable;
for(int i=0;i<n;i++){
if(key[i]==' ')
continue;
auto j=hashtable.find(key[i]);
if(j==hashtable.end()){
hashtable[key[i]]='a'+count;
count++;
}
}
for(int k=0;k<m;k++){
if(message[k]==' ')
s+=' ';
else{
s+=hashtable[message[k]];
}
}
return s;
}
};
//python
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
mp = {' ': ' '}
i = 0
for c in key:
if c not in mp:
mp[c] = ascii_lowercase[i]
i += 1
return ''.join(mp[c] for c in message)