algorithm notes: leetcode#804 unique morse code words

Problem


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, “cab” can be written as “-.-.-…-”, (which is the concatenation “-.-.” + “-…” + “.-”). We’ll call such a concatenation, the transformation of a word.

Return the number of different transformations among all words we have.

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 “–…--.”.

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.

Solution


Basic idea

Iterate all words, map each word to morse codes, use set to remove duplicates and count the length of the set, which is the number of distinct morse codes of words. To get morse code of one word, iterate each character, map it to morse code and combine morse codes of characters into morse code of the word.

Python implementation

1
2
3
4
5
6
7
8
9
10
class :
def uniqueMorseRepresentations(self, words):
"""
:type words: List[str]
:rtype: int
"""
morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",
".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",
".--","-..-","-.--","--.."]
return len(set(''.join(morse[ord(ch) - ord('a')]for ch in word) for word in words))

Java implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class {
public int uniqueMorseRepresentations(String[] words) {
String[] morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..",
".---","-.-",".-..","--","-.","---",".--.","--.-",".-.",
"...","-","..-","...-",".--","-..-","-.--","--.."};
Set<String> codes = new HashSet<>();
for(String word : words){
String code = "";
for(char ch : word.toCharArray()) { code += morse[ch - 'a']; }
codes.add(code);
}
return codes.size();
}
}

Time complexity analysis

Assuming that there are n characters in total, time complexity is O(n). The method above iterate each character of each word.

Space complexity analysis

Assuming there are n characters in total, space complexity is O(n). We iterate each character of each word and map it to morse code.


804. Unique Morse Code Words
804. 唯一摩尔斯密码词
(中文版) 算法笔记: 力扣#804 唯一摩尔斯密码词