题目
【 英文 】:International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: “a” maps to “.-”, “b” maps to “-…”, “c” maps to “-.-.”, and so on.
For convenience, the full table for the 26 letters of the English alphabet is given below:
[".-","-…","-.-.","-…",".","…-.","–.","…","…",".—","-.-",".-…","–","-.","—",".–.","–.-",".-.","…","-","…-","…-",".–","-…-","-.–","–…"]
Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, “cba” can be written as “-.-…–…”, (which is the concatenation “-.-.” + “-…” + “.-”). We’ll call such a concatenation, the transformation of a word.
【 题意 】:给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。例如,“cab” 可以写成 “-.-…–…”,(即 “-.-.” + “-…” + ".-"字符串的结合)。我们将这样一个连接过程称作单词翻译。
解题思路
分析题目无非就是去重的选择,两种方法
1、使用set容器
2、自己进行对比
参考解法
set容器
class Solution {
public:
int uniqueMorseRepresentations(vector<string>& words) {
set<string> re;
string strmap[26]={".-","-...","-.-.","-..",".","..-.","--.",
"....","..",".---","-.-",".-..","--","-.",
"---",".--.","--.-",".-.","...","-","..-",
"...-",".--","-..-","-.--","--.."};
for(string str:words){
string restr;
for(char c:str){
restr+=strmap[c-'a'];
}
re.insert(restr);
}
return re.size();
}
};
排序去重
class Solution {
public:
string dic[26] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
int uniqueMorseRepresentations(vector<string>& words) {
if(words.size() == 0)
return 0;
vector<string> results;
for(int i=0;i<words.size();i++){
string temp = "";
for(int j=0;j<words[i].length();j++){
temp += dic[words[i][j]-'a'];
}
results.push_back(temp);
}
sort(results.begin(),results.end());
int count = 1;
string cmp = results[0];
for(int i=0;i<results.size();i++){
if(results[i] != cmp){
count++;
cmp = results[i];
}
}
return count;
}
};
总结
set
- c++中的std::set,是基于红黑树的平衡二叉树的数据结构实现的一种容器,因为其中所包含的元素的值是唯一的,因此主要用于去重和排序。
- set用法
更优解
- 使用排序去重会有更优的时间复杂度
- 每次insert,delete的话,红黑树需要一些时间来调整结构,有时间和空间的开销。