我的想法是建立一个从单个字符到摩尔码的map,这样对所有words里单词直接映射得到相应摩尔码,再全部插入一个set中就自动去重了。(注意char到string要经过转换)
int uniqueMorseRepresentations(vector<string>& words)
{
vector<string> code = { ".-","-...","-.-.","-..",".","..-.","--.","....",
"..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-",
"...-",".--","-..-","-.--","--.." };
vector<string> letter = { "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" };
map<string, string> letter2code;
for (int i = 0; i < 26; ++i)
letter2code[letter[i]] = code[i];
set<string> transcode;
for (auto iter = words.begin(); iter != words.end(); ++iter)
{
string s = *iter;
string code = "";
for (int i = 0; i < s.length(); ++i)
{
string a(1, s[i]);
code += letter2code[a];
}
transcode.insert(code);
}
return transcode.size();
}
看了别人答案发现不用一个map,直接用char-‘a’就能表示一个char的对应摩尔码的索引
int uniqueMorseRepresentations(vector<string>& words) {
vector<string> lookup = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
unordered_set<string> hm;
int ct=0;
for (int i=0; i<words.size(); i++) {
string str ="";
for (int j=0;j<words[i].size(); j++) {
str += (lookup[(words[i][j] -'a')]);
}
if (hm.count(str) == 0) {
hm.insert(str);
}
}
return hm.size();
}