原题链接: Leetcode 804. Unique Morse Code Words
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:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
Given an array of strings words
where each word can be written as a concatenation of the Morse code of each letter.
For example, “cab” can be written as “-.-…–…”, which is the concatenation of “-.-.”, “.-”, and “-…”. We will call such a concatenation the transformation of a word.
Return the number of different transformations among all words we have.
Example 1:
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 "--...--.".
Example 2:
Input: words = ["a"]
Output: 1
方法一:哈希表
思路:
题目问的就是给定一些单词,问他们的摩尔斯编码去重后还有多少种。
哈希表unordered_set可以自动实现去重,只要将单词转化后插入,最后输出哈希表的大小即可
c++代码:
const static string a[] = {
".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..", "--", "-.",
"---", ".--.", "--.-", ".-.", "...", "-", "..-",
"...-", ".--", "-..-", "-.--", "--.."
};
class Solution {
public:
int uniqueMorseRepresentations(vector<string>& words) {
unordered_set<string> s;
for(auto w : words){
string ans;
for(auto c : w){
ans += a[c - 'a'];
}
s.insert(ans);
}
return s.size();
}
};
复杂度分析:
- 时间复杂度:O(S) ,S为所有单词的长度之和
- 空间复杂度:O(S) ,S为所有单词的长度之和