Leetcode——820. 单词的压缩编码

题目传送门
思路一:暴力,将字符串按字符个数从大到小排列,然后判断后续字符串是否是匹配字符串的子串。

class Solution
{
public:
    int minimumLengthEncoding(vector<string>& words)
    {
        string str="";
        int lengths=words.size();
        priority_queue<pair<int,int> > pq;
        for(int i=0;i<lengths;i++)
        {
            int templength=words[i].length();
            pq.push(make_pair(templength,i));
        }
        while(!pq.empty())
        {
            string tempstr=words[pq.top().second];
            tempstr+="#";
            pq.pop();
            if(str.find(tempstr)==string::npos)
            {
                str+=tempstr;
            }
        }
        return str.length();
    }
};

思路二:字典树(注意现在其实是字符串的倒序匹配)

class Treenode
{
public:
    Treenode* children[26];
    Treenode()
    {
        for(int i=0;i<26;i++)
        {
            children[i]=NULL;
        }
    }

};

class Tri
{
public:
    Treenode* root;
    Tri()
    {
       root=new Treenode();
    }
    int insertstr(string s)
    {
        Treenode* tnode=root;
        bool isnew=false;
        int strlength=s.length();
        for(int i=strlength-1;i>=0;i--)
        {
            int index=int(s[i]-'a');
            if(tnode->children[index]==NULL)
            {
                isnew=true;
                tnode->children[index]=new Treenode();
            }
            tnode=tnode->children[index];
        }
        if(isnew)
        {
            return strlength+1;
        }
        else
        {
            return 0;
        }
    }
};
class Solution
{
public:
    int minimumLengthEncoding(vector<string>& words)
    {
        int re=0;
        int lengths=words.size();
        priority_queue<pair<int,int> > pq;
        for(int i=0;i<lengths;i++)
        {
            int templength=words[i].length();
            pq.push(make_pair(templength,i));
        }
        Tri* t=new Tri();
        while(!pq.empty())
        {
            string tempstr=words[pq.top().second];
            re=re+t->insertstr(tempstr);
            pq.pop();
        }
        return re;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值