1. 程式人生 > >Leetcode刷題筆記python唯一摩爾斯密碼詞

Leetcode刷題筆記python唯一摩爾斯密碼詞

唯一摩爾斯密碼詞

#題目

國際摩爾斯密碼定義一種標準編碼方式,將每個字母對應於一個由一系列點和短線組成的字串, 比如: “a” 對應 “.-”, “b” 對應 “-…”, “c” 對應 “-.-.”, 等等。

為了方便,所有26個英文字母對應摩爾斯密碼錶如下:

[".-","-…","-.-.","-…",".","…-.","–.","…","…",".—","-.-",".-…","–","-.","—",".–.","–.-",".-.","…","-","…-","…-",".–","-…-","-.–","–…"] 給定一個單詞列表,每個單詞可以寫成每個字母對應摩爾斯密碼的組合。例如,“cab” 可以寫成 “-.-.-…-”,(即 “-.-.” + “-…” + ".-"字串的結合)。我們將這樣一個連線過程稱作單詞翻譯。

返回我們可以獲得所有詞不同單詞翻譯的數量。

例如: 輸入: words = [“gin”, “zen”, “gig”, “msg”] 輸出: 2 解釋: 各單詞翻譯如下: “gin” -> “–…-.” “zen” -> “–…-.” “gig” -> “–…--.” “msg” -> “–…--.”

共有 2 種不同翻譯, “–…-.” 和 “–…--.”.

注意:

單詞列表words 的長度不會超過 100。 每個單詞 words[i]的長度範圍為 [1, 12]。 每個單詞 words[i]只包含小寫字母。

#解答

程式碼:

class Solution:
    def uniqueMorseRepresentations(self, words):
        """
        :type words: List[str]
        :rtype: int
        """
        MR=[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        AP='abcdefghijklmnopqrstuvwxyz'
        direct={}
        for i in range(26):
            direct[AP[i]]=MR[i]
        mrs_s=[]
        for i in words:
            mrs=''
            for j in i:
                mrs+=direct[j]
            mrs_s.append(mrs)
        num=len(set(mrs_s))
        return num

利用python的set() 功能 可以消除重複