804. Unique Morse Code Words

题目网址:https://leetcode.com/problems/unique-morse-code-words/description/
大意:求一个数组里面的字母所翻译的摩尔斯电码具体有多少种(难道莫尔斯电码的重复性这么高?=。=)
其实很简单,求一个list里面的unique list只要用set(list)就行了,再len()一下就是多少种了。

import string
class Solution:
    s = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
    def uniqueMorseRepresentations(self, words):
        """
        :type words: List[str]
        :rtype: int
        """
        MoseList = []
        mylist = []
        for item in words:
            MoseString = ''
            for character in item:
                index = string.ascii_lowercase.index(character)
                MoseString += self.s[index]
            MoseList.append(MoseString)
            mylist = set(MoseList)
        return len(mylist)

a = Solution()
print(a.uniqueMorseRepresentations(["gin", "zen", "gig", "msg"]))

但是这里我取巧了一下。import string库。这个库的ascii_lowercase方法(python 2 改为lowercase)方法可以返回这个字母在字母表里面的顺序。当然,也可以自己写一个lamba来操作(类似于ES6里面的箭头函数,起到一个匿名函数的作用)

def uniqueMorseRepresentations2(self, words):
        """
        :type words: List[str]
        :rtype: int
        """
        moorse = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.",
                  "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
        trans = lambda x: moorse[ord(x) - ord('a')]
        map_word = lambda word: ''.join([trans(x) for x in word])
        res = map(map_word, words)
        return len(set(res))

所有题目解题方法和答案代码地址:https://github.com/fredfeng0326/LeetCode
    原文作者:fred_33c7
    原文地址: https://www.jianshu.com/p/30df8b541ec0
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞