804. 唯一摩尔斯密码词

 

思路:
逐个翻译每个单词的摩斯码,若result[]中不存在相投的摩斯码,则存入;否则翻一下一个单词;
返回result[]的有效长度;
 1 class Solution(object):
 2     def uniqueMorseRepresentations(self, words):
 3         """
 4         :type words: List[str]
 5         :rtype: int
 6         """
 7         mosiPsw = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.",
 8                    "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
 9         # 存放各单词的摩斯码,不超过100个单词
10         result = [""]*100
11         # result的下标:result的有效长度
12         sub = 0
13         # 遍历words
14         for i in range(len(words)):
15             # 重置摩斯码
16             res = ""
17             # 遍历单词的字符
18             for index, ch in enumerate(words[i]):
19                 res += mosiPsw[ord(ch) - ord('a')]
20             # print(words[i], res)
21             # 将翻译的单词的摩斯码存到list中
22             if res not in result:
23                 result[sub] = res
24                 # 下标加1
25                 sub += 1
26             else:
27                 continue
28         return sub
29 
30 
31 if __name__ == '__main__':
32     solution = Solution()
33     print(solution.uniqueMorseRepresentations(["gin", "zen", "gig", "msg"]))
 
原文地址:https://www.cnblogs.com/panweiwei/p/12697818.html