前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >2.leetcode唯一的摩斯密码

2.leetcode唯一的摩斯密码

作者头像
py3study
发布2020-01-02 16:42:17
3850
发布2020-01-02 16:42:17
举报
文章被收录于专栏:python3

1.题目 International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on.

For convenience, the full table for the 26 letters of the English alphabet is given below:

代码语言:javascript
复制
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]

Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, "cba" can be written as "-.-..--...", (which is the concatenation "-.-." + "-..." + ".-"). We'll call such a concatenation, the transformation of a word.

Return the number of different transformations among all words we have.

代码语言:javascript
复制
Example:
Input: words = ["gin", "zen", "gig", "msg"]
Output: 2
Explanation: 
The transformation of each word is:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."

There are 2 different transformations, "--...-." and "--...--.".
  1. 自己的解决方法
代码语言:javascript
复制
class Solution:
    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        final_set = set()
        mosLIst = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        for word in words:
            temp = ''
            for i in word:
                temp += mosLIst[ord(i)-97]
            final_set.add(temp)
        return len(final_set)

Runtime: 36 ms, faster than 97.45% of Python3 online submissions for Unique Morse Code Words. Memory Usage: 12.9 MB, less than 5.36% of Python3 online submissions for Unique Morse Code Words.

3.其他解决方法

代码语言:javascript
复制
const codes = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]

const getIdx = char => char.charCodeAt(0) - 'a'.charCodeAt(0)

var uniqueMorseRepresentations = function(words) {
    return words.map( word => word.split('')
                                 .map( char => codes[getIdx(char)])
                                 .join(''))
                .reduce((set, cur) => set.add(cur), new Set())
                .size
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/10/12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档