编程语言
python
基本思路
- 创建一个字典,键为字母,值为摩斯码。
- 对于给出的单词,遍历每个单词里面的字母,从字典中找出对应的摩斯码,形成每个单词的摩斯码
- 将所有的摩斯码添加到一个列表中
- 通过将列表转为集合进行去重
- 返回集合的长度
代码实现
class Solution:
"""
804, 唯一的摩斯密码
"""
def uniqueMorseRepresentations(self, words:list) -> int:
mose_code = [".-","-...","-.-.","-..",".","..-.",
"--.","....","..",".---","-.-",".-..","--",
"-.","---",".--.","--.-",".-.","...","-","..-",
"...-",".--","-..-","-.--","--.."]
alpha = [chr(i) for i in range(97,123)]
my_dic = dict(zip(alpha,mose_code))
# 打印看一下
# for key,val in my_dic.items():
# print(key,val)
ans = []
for word in words:
coding = ""
for achar in word:
coding +=my_dic[achar]
ans.append(coding)
return len(set(ans))
s = Solution()
words = ["gin", "zen", "gig", "msg"]
ans = s.uniqueMorseRepresentations(words)
print(ans)