leecode [唯一摩尔斯密码词]
Posted john-geek-2018
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)
如有问题欢迎批评指正。
以上是关于leecode [唯一摩尔斯密码词]的主要内容,如果未能解决你的问题,请参考以下文章