1、题目
国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如:
‘a’ 对应 “.-” ,
‘b’ 对应 “-…” ,
‘c’ 对应 “-.-.” ,以此类推。
为了方便,所有 26 个英文字母的摩尔斯密码表如下:
[“.-”,“-…”,“-.-.”,“-…”,“.”,“…-.”,“–.”,“…”,“…”,“.—”,“-.-”,“.-…”,“–”,“-.”,“—”,“.–.”,“–.-”,“.-.”,“…”,“-”,“…-”,“…-”,“.–”,“-…-”,“-.–”,“–…”]
给你一个字符串数组 words ,每个单词可以写成每个字母对应摩尔斯密码的组合。
例如,“cab” 可以写成 “-.-…–…” ,(即 “-.-.” + “.-” + “-…” 字符串的结合)。我们将这样一个连接过程称作 单词翻译 。
对 words 中所有单词进行单词翻译,返回不同 单词翻译 的数量。
示例 1:
输入: words = [“gin”, “zen”, “gig”, “msg”]
输出: 2
解释:
各单词翻译如下:
“gin” -> “–…-.”
“zen” -> “–…-.”
“gig” -> “–…–.”
“msg” -> “–…–.”
共有 2 种不同翻译, “–…-.” 和 “–…–.”.
示例 2:
输入:words = [“a”]
输出:1
提示:
1 <= words.length <= 100
1 <= words[i].length <= 12
words[i] 由小写英文字母组成
2、解
首先通过map将字母表与morse密码进行映射;再对words进行遍历并通过map进行存储,最后map.size()即为答案。
int uniqueMorseRepresentations(vector<string> &words)
{
vector<string> morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.",
"---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
unordered_map<char, string> morseWords;
for(int i = 0; i < 26; i ++){
morseWords[i + 'a'] = morse[i];
}
unordered_map<string, int> result;
for(auto word : words){
string temp = "";
for(auto w : word){
temp.append(morseWords[w]);
}
result[temp]++;
}
return result.size();
}
改进
博主最初通过map对字母与密码进行映射,其实完全没必要,遍历words的word时,对word的每个字母进行-‘a’
操作得到索引值即可对应为morse数组中的对应string密码;同时直接通过set来存储不需要计数各个元素的出现次数;并将morse数组定义为固定内存空间const static 。
const static string morse[26] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.",
"---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
class Solution {
public:
int uniqueMorseRepresentations(vector<string>& words) {
unordered_set<string> result;
for(auto word : words){
string temp = "";
for(auto w : word){
temp.append(morse[w - 'a']);
}
result.emplace(temp);
}
return result.size();
}
};