题目描述:
a-z都有对应的莫斯密码
为:
[“.-“,”-…”,”-.-.”,”-..”,”.”,”..-.”,”–.”,”….”,”..”,”.—”,”-.-“,”.-..”,”–”,”-.”,”—”,”.–.”,”–.-“,”.-.”,”…”,”-“,”..-“,”…-“,”.–”,”-..-“,”-.–”,”–..”]
Example:
Input: words = ["gin", "zen", "gig", "msg"]
Output: 2
Explanation:
The transformation of each word is:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."
There are 2 different transformations, "--...-." and "--...--.".
即找到这个words中使用变换得到不同的莫斯密码。
Note:
The length of words will be at most 100.
Each words[i] will have length in range [1, 12].
words[i] will only consist of lowercase letters.
最佳实践:
对words中每一个string中都转为莫斯密码,放入c++的标准库中的unordered_set容器中,此处注意是无序容器,对于无序容器,由于无需维护元素的顺序,故效率比set容器高。无序容器是用Hash函数进行对关键字的组织的,底层数据结构为红黑树。
class Solution {
public:
vector<string> code={".-","-...","-.-.","-..",".",
"..-.","--.","....","..",".---",
"-.-",".-..","--","-.","---",".--.",
"--.-",".-.","...","-","..-","...-",
".--","-..-","-.--","--.."};
int uniqueMorseRepresentations(vector<string>& words)
{
int res = 0;
unordered_set<string> unique_code;
for(const auto &i:words)
{
string wordcode;
for(auto c:i)
{
wordcode += code[c-'a'];
}
unique_code.insert(wordcode);
}
return unique_code.size();
}
};
运行例子耗时:6ms
本文介绍了一种算法,用于计算一组单词转换为莫尔斯电码后的不同组合数量。通过对每个单词中的字母映射到特定的莫尔斯电码,并利用C++标准库中的unordered_set容器来统计不重复的变换结果。
428

被折叠的 条评论
为什么被折叠?



