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 "--...--."
简单看下题目。这道题是要求我们 1.实现摩斯密码的转换 2.返回唯一值的数量
思路
1.先创建一个字段保存26个字母所以及所对应的摩斯密码
2.使用循环将list中的string转换成摩斯密码
3.转换成set类型之后判断唯一(set的值一定是唯一的,相当于去除了重复)
以下是Python解法
class Solution:
def uniqueMorseRepresentations(self, words):
"""
:type words: List[str]
:rtype: int
"""
key = [chr(i) for i in range(97,123)]#得到一个含有26位小写字母的list
value = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
dic = {}
for i in range(len(key)):#创建字母对应的摩尔密码字典
dic[key[i]] = value[i]
fina = []
for i in words:
cur = ''
for j in i:
cur += dic[j]
fina.append(cur)
return len(set(fina))
注意:虽然用到了两次循环。但是时间复杂度其实是O(n).第二次循环是在word中的每个元素中遍历,并不是等于n