「唯一摩尔斯密码词」| leetcode 刷题011

版权声明:转载请注明出处 https://blog.csdn.net/sixkery/article/details/81877146

题目

国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如: "a" 对应 ".-", "b" 对应 "-…", "c" 对应 "-.-.", 等等。

为了方便,所有26个英文字母对应摩尔斯密码表如下:

[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]

给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。例如,"cab" 可以写成 "-.-.-….-",(即 "-.-." + "-…" + ".-"字符串的结合)。我们将这样一个连接过程称作单词翻译。

返回我们可以获得所有词不同单词翻译的数量。

例如:
输入: words = ["gin", "zen", "gig", "msg"]
输出: 2
解释:
各单词翻译如下:
"gin" -> "--…-."
"zen" -> "--…-."
"gig" -> "--…--."
"msg" -> "--…--."

共有 2 种不同翻译, "--…-." 和 "--…--.".

注意:

  • 单词列表words 的长度不会超过 100。
  • 每个单词 words[i]的长度范围为 [1, 12]。
  • 每个单词 words[i]只包含小写字母。

解答

先上代码再解释。

class Solution(object):
    def uniqueMorseRepresentations(self, words):
        """
        :type words: List[str]
        :rtype: int
        """

        m = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        w = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
        d = dict(zip(w,m))


        temp = set()


        for index in words:
            b = []

            for i in index:

                b.append(d[i])

            s = ''.join(b)

            temp.add(s)

        return len(temp)

首先通过 zip 方法构造一个字典,目的是为了让字母和摩尔斯密码一一对应,然后遍历传入的单词,第二层循环遍历单词的字母
再把字母对应的摩尔斯密码传入列表,拼接成字符串传入set中,计算长度即可。
再来改进一下代码。

class Solution(object):
    def uniqueMorseRepresentations(self, words):
        """
        :type words: List[str]
        :rtype: int
            """
        m = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        w = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
        d = dict(zip(w,m))

        res = []

        for index in words:
            s = ''
            for i in index:

                s = s + d.get(i)
            res.append(s)

        return len(set(res))

基本上一样,相对来说更好理解一点。

猜你喜欢

转载自blog.csdn.net/sixkery/article/details/81877146