Leetcode刷题 804. Unique Morse Code Words

题目

【 英文 】: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, “cba” can be written as “-.-…–…”, (which is the concatenation “-.-.” + “-…” + “.-”). We’ll call such a concatenation, the transformation of a word.
【 题意 】:给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。例如,“cab” 可以写成 “-.-…–…”,(即 “-.-.” + “-…” + ".-"字符串的结合)。我们将这样一个连接过程称作单词翻译。

解题思路

分析题目无非就是去重的选择,两种方法
1、使用set容器
2、自己进行对比

参考解法

set容器

class Solution {
public:
    int uniqueMorseRepresentations(vector<string>& words) {
        set<string> re;
        string strmap[26]={".-","-...","-.-.","-..",".","..-.","--.",
                         "....","..",".---","-.-",".-..","--","-.",
                         "---",".--.","--.-",".-.","...","-","..-",
                         "...-",".--","-..-","-.--","--.."};
        for(string str:words){
            string restr;
            for(char c:str){
                restr+=strmap[c-'a'];
            }
            re.insert(restr);
        }
        return re.size();
    }
};

排序去重

class Solution {
public:
    string dic[26] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
    int uniqueMorseRepresentations(vector<string>& words) {
        if(words.size() == 0)
            return 0;
        vector<string> results;
        for(int i=0;i<words.size();i++){
            string temp = "";
            for(int j=0;j<words[i].length();j++){
                temp += dic[words[i][j]-'a'];
            }
            results.push_back(temp);
        }
        sort(results.begin(),results.end());
        int count = 1;
        string cmp = results[0];
        for(int i=0;i<results.size();i++){
            if(results[i] != cmp){
                count++;
                cmp = results[i];
            }

        }
        return count;
    }
};

总结

set

  • c++中的std::set,是基于红黑树的平衡二叉树的数据结构实现的一种容器,因为其中所包含的元素的值是唯一的,因此主要用于去重和排序。
  • set用法

更优解

  • 使用排序去重会有更优的时间复杂度
  • 每次insert,delete的话,红黑树需要一些时间来调整结构,有时间和空间的开销。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值