前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode-804-Unique Morse Code Words

leetcode-804-Unique Morse Code Words

作者头像
chenjx85
发布2018-05-21 18:19:46
3740
发布2018-05-21 18:19:46
举报

题目描述:

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, "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.

代码语言: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 "--...--.".

Note:

  • The length of words will be at most 100.
  • Each words[i] will have length in range [1, 12].
  • words[i] will only consist of lowercase letters.

要完成的函数:

int uniqueMorseRepresentations(vector<string>& words) 

说明:

1、这道题给定一个vector,里面存放着多个字符串,字符串中的每一个字母都对应一个摩尔斯码。要求把给定的字符串翻译成摩尔斯码,最后返回有多少种不同的摩尔斯码。

2、明白题意,这道题也没有什么快速的方法来实现,就直接暴力解法做吧。

外层循环,取出每个字符串。

内层循环,取出字符串中的逐个字母,一一对照着翻译成摩尔斯码,最终结果存储在新定义的string中,把string一一加入到set中。

最后返回set的个数就可以了。

代码如下:

代码语言:javascript
复制
    int uniqueMorseRepresentations(vector<string>& words) 
    {
        set<string>res;//存储翻译之后的摩尔斯码
        vector<string>morse={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
        int s1=words.size(),s2;
        string t;//临时变量
        for(int i=0;i<s1;i++)//逐一取出字符串
        {
            s2=words[i].size();
            t="";
            for(int j=0;j<s2;j++)//逐一取出字母
                t+=morse[words[i][j]-'a'];//翻译成摩尔斯码
            res.insert(t);//存储到set中
        }
        return res.size();
    }

上述代码逻辑清晰,实测6ms,beats 99.70% of cpp submissions。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-05-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
  • 要完成的函数:
  • 说明:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档