1. 程式人生 > >leecode [唯一摩爾斯密碼詞]

leecode [唯一摩爾斯密碼詞]

今天看到leecode [唯一摩爾斯密碼詞]比較有趣,但發現網頁上一處錯誤,如下:

根據原文定義"cab"對應的摩斯密碼應該是"-.-..--...",已經聯絡leecode人員改正。

具體步驟簡單分解為:
1、將26個字母及對應的摩斯密碼做成字典表
2、以單詞為單位去查字典表,將字母對應摩斯密碼首尾連線,返回單詞對應的莫斯字串
3、自定義一個空的字典morse_words = {},對給定的單詞陣列遍歷呼叫第2步,但遍歷中需要判斷單詞
對應的莫斯字串是否在morse_words中
對應Python程式碼如下:

 

def morse_decode(single_wd):
encode_ms = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.",
"---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
ws = ['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']
maps = {}
cnt = len(encode_ms)
for i in range(cnt):
maps[ws[i]] = encode_ms[i]
# print(encode_ms[i], ws[i])
# print(maps)
single_ms = ''
for i in range(len(single_wd)):
char = single_wd[i]
char_morse = maps.get(char)
single_ms += char_morse
# print(w, m)
print(single_wd, single_ms)
return single_ms


def morse_distinct(words):
morse_words = {}
for w in words:
morse_word = morse_decode(single_wd=w)
print(morse_word)
if morse_word not in morse_words.values():
morse_words[w] = morse_word
print(morse_words)
return len(morse_words)


if (__name__=='__main__'):
# main()
words = ["gin", "zen", "gig", "msg"]
morse_decode(single_wd='cab')
cnt = morse_distinct(words=words)
print('distinct morse encode: ', cnt)

如有問題歡迎批評指正。