题目描述
国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如: “a” 对应 “.-”, “b” 对应 “-…”, “c” 对应 “-.-.”, 等等。
为了方便,所有26个英文字母对应摩尔斯密码表如下:
[".-","-…","-.-.","-…",".","…-.","–.","…","…",".—","-.-",".-…","–","-.","—",".–.","–.-",".-.","…","-","…-","…-",".–","-…-","-.–","–…"]
给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。例如,“cab” 可以写成 “-.-…–…”,(即 “-.-.” + “.-” + “-…” 字符串的结合)。我们将这样一个连接过程称作单词翻译。
返回我们可以获得所有词不同单词翻译的数量
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/unique-morse-code-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
C++
class Solution {
public:
int uniqueMorseRepresentations(vector<string>& words) {
/*
思路:
先将26个字母对应的编码用哈希表存储;
将输入的单词翻译,存入到数组;
对于数组中的翻译,按照频率存储到一个新的哈希表;
返回新的哈希表的长度就可以
*/
char a[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
vector<string> b={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
unordered_map <char,string> match;
//初始化,将26个字母对应的字符串存储到哈希表,用于以后翻译时查询;
for(int i=0;i<26;i++){
match[a[i]]=b[i];
}
vector<string> answer; //数组用于存储,翻译后的所有单词
for(int i=0;i<words.size();i++){
string this_word=words[i];
string temp="";
for(int j=0;j<this_word.size();j++){
temp+=match[this_word[j]];
}
answer.push_back(temp);
}
//新建一个哈希表,用于存储翻译的数量;
unordered_map <string,int> this_end;
for(int i=0;i<answer.size();i++){
if(this_end.find(answer[i])!=this_end.end()){
this_end[answer[i]]++;
}else{
this_end[answer[i]]=1;
}
}
return this_end.size();
}
};