您当前的位置: 首页 >  leetcode

孑渡

暂无认证

  • 1浏览

    0关注

    178博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【Leetcode】每日一题:唯一摩尔斯密码词

孑渡 发布时间:2022-04-10 18:48:15 ,浏览量:1

唯一摩尔斯密码词

国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如: ‘a’ 对应 “.-” , ‘b’ 对应 “-…” , ‘c’ 对应 “-.-.” ,以此类推。 为了方便,所有 26 个英文字母的摩尔斯密码表如下: [“.-”,“-…”,“-.-.”,“-…”,“.”,“…-.”,“–.”,“…”,“…”,“.—”,“-.-”,“.-…”,“–”,“-.”,“—”,“.–.”,“–.-”,“.-.”,“…”,“-”,“…-”,“…-”,“.–”,“-…-”,“-.–”,“–…”] 给你一个字符串数组 words ,每个单词可以写成每个字母对应摩尔斯密码的组合。 例如,“cab” 可以写成 “-.-…–…” ,(即 “-.-.” + “.-” + “-…” 字符串的结合)。我们将这样一个连接过程称作 单词翻译 。 对 words 中所有单词进行单词翻译,返回不同 单词翻译 的数量。 来源:力扣(LeetCode)

AC代码
class Solution:
    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        tempstr = 'abcdefghijklmnopqrstuvwxyz'
        mros = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        result = []
        for w in words:
            temp = ''
            for letter in w:
                temp += mros[tempstr.find(letter)]
            if temp not in result:
                result.append(temp)
        return len(result)
官方代码
MORSE = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
         "....", "..", ".---", "-.-", ".-..", "--", "-.",
         "---", ".--.", "--.-", ".-.", "...", "-", "..-",
         "...-", ".--", "-..-", "-.--", "--.."]

class Solution:
    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        return len(set("".join(MORSE[ord(ch) - ord('a')] for ch in word) for word in words))


# 作者:LeetCode-Solution
关注
打赏
1663211900
查看更多评论
立即登录/注册

微信扫码登录

0.0382s