LeetCode804. Unique Morse Code Words

我的想法是建立一个从单个字符到摩尔码的map,这样对所有words里单词直接映射得到相应摩尔码,再全部插入一个set中就自动去重了。(注意char到string要经过转换)

    int uniqueMorseRepresentations(vector<string>& words) 
    {
        vector<string> code = { ".-","-...","-.-.","-..",".","..-.","--.","....",
            "..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-",
            "...-",".--","-..-","-.--","--.." };
        vector<string> letter = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
            "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };

        map<string, string> letter2code;
        for (int i = 0; i < 26; ++i)
            letter2code[letter[i]] = code[i];

        set<string> transcode;

        for (auto iter = words.begin(); iter != words.end(); ++iter)
        {
            string s = *iter;
            string code = "";
            for (int i = 0; i < s.length(); ++i)
            {
                string a(1, s[i]);
                code += letter2code[a];
            }

            transcode.insert(code);
        }

        return transcode.size();
    }

看了别人答案发现不用一个map,直接用char-‘a’就能表示一个char的对应摩尔码的索引

    int uniqueMorseRepresentations(vector<string>& words) {
    vector<string> lookup = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
    unordered_set<string> hm;
    int ct=0;
    for (int i=0; i<words.size(); i++) {
        string str ="";
        for (int j=0;j<words[i].size(); j++) {
            str += (lookup[(words[i][j] -'a')]);
        }
        if (hm.count(str) == 0) {
            hm.insert(str);
        }
    }
        return hm.size();
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值