804. Unique Morse Code Words

作者: fred_33c7 | 来源:发表于2018-06-20 18:05 被阅读0次

    原文网址: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))
    

    相关文章

      网友评论

        本文标题:804. Unique Morse Code Words

        本文链接:https://www.haomeiwen.com/subject/elbxyftx.html