LeetCode804. 唯一のモールス暗号語

3913 ワード

タイトルの説明:
国際モールス暗号は、「a」が「.-」、「b」が「-...」など、一連の点と短線からなる文字列に対応する標準的な符号化方法を定義します.「c」は「-.-.」に対応し、などなど.
便宜上、26文字の英語アルファベットは以下の通りです.
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] 単語のリストを指定します.各単語は、モールスパスワードに対応するアルファベットの組み合わせとして書くことができます.たとえば、「cab」は「-.-.-..--...」と書くことができます.(「-.-.」+"-..."+ 「.-」文字列の結合).このような接続プロセスを単語翻訳と呼びます.
すべての語の異なる単語の翻訳を得ることができる数を返します.
例えば、入力:words=["gin","zen","gig","msg"]出力:2解釈:各単語は以下のように訳される:“gin”--->「--...-.」"zen"-> "--...-.""gig"-> "--...--.""msg"-> "--...--."
全部で2種類の異なる翻訳があります.と「--......」.注意:
単語リストwordsの長さは100を超えません.各単語words[i]の長さ範囲は[1,12]である.各単語words[i]には小文字のみが含まれている.
問題解決の考え方:
chrを使用してアルファベットを所与のモルスコープテーブルに対応するパスワードにマッピングし、パスワードを文字列に変換し、セットsetを使用して再ロードします.
いくつかのコードを整理して収集しました.
class Solution:
    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        Morse_Code_dict = {'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': '--..'}   #      
        set_num = set()   #      
        for i in range(len(words)):  #      
            s = ""
            for j in words[i]:  #           
                s += Morse_Code_dict[j]
            set_num.add(s)    #      
        return len(set_num)   #      

または、
def uniqueMorseRepresentations(self, words: List[str]) -> int:
        mos = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        alph = "abcdefghijklmnopqrstuvwxyz"
        alph_mos = dict(zip(alph,mos))
        res = set()
        for word in words:
            s = ""
            for i in word:
                s = s + alph_mos[i]
            res.add(s)
        return len(res)

または、
class Solution:
    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        mode = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
                "....", "..", ".---", "-.-", ".-..", "--", "-.", "---",
                ".--.", "--.-", ".-.", "...", "-", "..-", "...-",
                ".--", "-..-", "-.--", "--.."]
        ss = set()
        for i in words: #      
            s = ''
            for j in i: #            
                s += mode[ord(j) - 97]
            ss.add(s)
        return len(ss) #       

以上の3つの全体的な考え方は同じであるが,文字とモルスコープ間の対応処理方法が異なるだけである.