【leetcode】804. Unique Morse Code Words


这题一直困扰我的地方在于题干‘cab’的编码,怎么看都是编码成了‘cba’。。搜索很久没人提出困惑,写完看了discuss果然高居榜首的就是这个描述的质疑。

一直找有没有字母转ascci码的操作然后直接相减就可以得到index,但没找到

import string
class Solution(object):
    def uniqueMorseRepresentations(self, words):
        """
        :type words: List[str]
        :rtype: int
        """
        code = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        ch = string.ascii_letters[:26]
        code_dict = {}
        for i in range(26):
            code_dict[ch[i]] = code[i]
        mydict = {}
        for word in words:
            word_collect = ''
            for w in word:
                word_collect += code_dict[w]
            mydict[word_collect] = 1
        return len(mydict)

43ms python 41.68%

----------------------------------

从discuss中发现了ord()函数,返回ascci码值,最后一句话就能解决不过判定效果是一样的

import string
class Solution(object):
    def uniqueMorseRepresentations(self, words):
        """
        :type words: List[str]
        :rtype: int
        """
        code = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        return len({''.join((code[ord(i)-ord('a')]) for i in word) for word in words})
43ms 41.68%

猜你喜欢

转载自blog.csdn.net/u014381464/article/details/80642632