Leetcode 804. Unique Morse Code Words python

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:

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

Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, "cab" 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.

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.实现摩斯密码的转换 2.返回唯一值的数量

思路

1.先创建一个字段保存26个字母所以及所对应的摩斯密码

2.使用循环将list中的string转换成摩斯密码

3.转换成set类型之后判断唯一(set的值一定是唯一的,相当于去除了重复)

以下是Python解法

class Solution:
    def uniqueMorseRepresentations(self, words):
        """
        :type words: List[str]
        :rtype: int
        """
        key = [chr(i) for i in range(97,123)]#得到一个含有26位小写字母的list
        
        value = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        
        dic = {}
        
        for i in range(len(key)):#创建字母对应的摩尔密码字典
            dic[key[i]] = value[i]
        fina = []
        
        for i in words:
            cur = ''
            for j in i:
                cur += dic[j]
            fina.append(cur)
            
        return len(set(fina))
注意:虽然用到了两次循环。但是时间复杂度其实是O(n).第二次循环是在word中的每个元素中遍历,并不是等于n


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值