題目要求
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.
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.
Return the number of different transformations among all words we have.
題目分析及思路
題目給出摩斯碼的編碼規則,要求傳回所有單詞不同transformation的個數。找出多少種不同的情況,可以用len(set())的方式進行處理。摩斯碼和字母的對應關系可以用字典。
python代碼
class Solution:
def uniqueMorseRepresentations(self, words):
"""
:type words: List[str]
:rtype: int
"""
morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
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']
mldict = dict(zip(letter,morse))
res = set()
for word in words:
mword = ""
for w in word:
mword = mword + mldict[w]
res.add(mword)
return len(res)
轉載于:https://www.cnblogs.com/yao1996/p/10212454.html