LeetCode804. 唯一摩尔斯密码词

题目描述:

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

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

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

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

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

共有 2 种不同翻译, "--...-." 和 "--...--.".
注意:

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

解题思路:

利用chr将字母映射到给定摩尔斯密码表中对应密码,然后将密码转换成字符串,利用集合set去重。

整理收集了几个代码如下:

class Solution:
    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        Morse_Code_dict = {'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': '--..'}   #摩尔斯密码表
        set_num = set()   #定义一个集合
        for i in range(len(words)):  #遍历每个单词
            s = ""
            for j in words[i]:  #遍历每个单词的每个字母
                s += Morse_Code_dict[j]
            set_num.add(s)    #添加到集合中
        return len(set_num)   #返回集合长度

或:

def uniqueMorseRepresentations(self, words: List[str]) -> int:
        mos = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        alph = "abcdefghijklmnopqrstuvwxyz"
        alph_mos = dict(zip(alph,mos))
        res = set()
        for word in words:
            s = ""
            for i in word:
                s = s + alph_mos[i]
            res.add(s)
        return len(res)

或:

class Solution:
    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        mode = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
                "....", "..", ".---", "-.-", ".-..", "--", "-.", "---",
                ".--.", "--.-", ".-.", "...", "-", "..-", "...-",
                ".--", "-..-", "-.--", "--.."]
        ss = set()
        for i in words: #遍历每个单词
            s = ''
            for j in i: # 遍历每个单词的每个字母
                s += mode[ord(j) - 97]
            ss.add(s)
        return len(ss) # 返回集合长度

以上三种整体思路是一样的,只是在字符与摩尔斯密码间的对应处理方法不同。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值