[leetcode]820. Short Encoding of Words

162 篇文章 0 订阅

[leetcode]820. Short Encoding of Words


Analysis

好冷鸭—— [每天刷题并不难0.0]

Given a list of words, we may encode it by writing a reference string S and a list of indexes A.
For example, if the list of words is [“time”, “me”, “bell”], we can write it as S = “time#bell#” and indexes = [0, 2, 5].
Then for each index, we will recover the word by reading from the reference string from that index until we reach a “#” character.
What is the length of the shortest reference string S possible that encodes the given words?
在这里插入图片描述
如果某个字符串是另一个字符串的后缀,则可以合并。先把每个字符串都翻转一下,然后再排序,最后判断每个字符串是否包含在其相邻字符串中就可以了。

Implement

class Solution {
public:
    int minimumLengthEncoding(vector<string>& words) {
        int len = words.size();
        for(int i=0; i<len; i++)
            reverse(words[i].begin(), words[i].end());
        sort(words.begin(), words.end());
        vector<string> words1;
        words1.push_back(words[len-1]);
        string tmp = words[len-1];
        for(int i=len-2; i>=0; i--){
            if(tmp.find(words[i]) == string::npos){
                tmp = words[i];
                words1.push_back(tmp);
            }
        }
        int res = 0;
        for(auto word:words1)
            res += word.size();
        res += words1.size();
        return res;
    }
};

下面是大神的巧妙做法,就是先把整个输入存在hash表中,然后删掉所有前缀,最后剩下的就是shortcode

class Solution {
public:
    int minimumLengthEncoding(vector<string>& words) {
        unordered_set<string> w(words.begin(), words.end());
        for(string word:w){
            for(int i=1; i<word.size(); i++)
                w.erase(word.substr(i));
        }
        int res = 0;
        for(string word:w)
            res += word.size()+1;
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值