国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如: "a" 对应 ".-", "b" 对应 "-...", "c" 对应 "-.-.", 等等。
为了方便,所有26个英文字母对应摩尔斯密码表如下:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。例如,"cab" 可以写成 "-.-..--...",(即 "-.-." + ".-" + "-..." 字符串的结合)。我们将这样一个连接过程称作单词翻译。
返回我们可以获得所有词不同单词翻译的数量。
例如:
输入: words = ["gin", "zen", "gig", "msg"]
输出: 2
解释:
各单词翻译如下:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."
共有 2 种不同翻译, "--...-." 和 "--...--.".
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/unique-morse-code-words
解题思路
主要用set的value唯一性
1.建立的的字符串存放26个字母对应的MORSE密码
2.遍历给出的字符串组words->单个word,然后取出word->单个字符ch,将字符映射回MORSE[],整个word转化存放到temp
3.temp插入到set中
class Solution {
public:
int uniqueMorseRepresentations(vector<string>& words) {
set<string> set_string;
string MORSE[] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
for(auto word:words)
{
string temp;
for(auto ch:word)
{
temp += MORSE[ch - 'a']; //该单词处于第几个字母
}
set_string.insert(temp);
}
return set_string.size();
}
};
学习到的点:
1.set<数据类型> ,忘记怎么定义set类型的数据了。
2.以及字符串组定义string a[] = {}。{}写成了[]。积累一下。