leetcode:820. 单词的压缩编码(前缀树)

题目:

在这里插入图片描述

分析:

可以采用前缀树思路解决

代码:

class Solution {
private:
 Solution* next[26] = { nullptr };
    int k=0;//不是结尾位0   是结尾为1.
public:
    Solution() {}
    void insert(const string& word,int &c)//插入单词
 {
  Solution* root = this;
        //尾部符号个数的计算
        int d=0;
        int dd=0;
        if(this->next[word[0] - 'a'] == nullptr) d=1;
  for (const auto& w : word) {
   if (root->next[w - 'a'] == nullptr) 
            {
                d++;
                c++;
                if(root->k==1) {
                        d=-(1<<30);root->k=0;
                }
                root->next[w - 'a'] = new Solution();
            }
            else dd++;
   root = root->next[w - 'a'];
  }
        cout<<d<<" "<<dd<<" "<<endl;
        for(int i=0;i<26;i++)
        {
           if(root->next[i]!=nullptr) return; 
        }
        root->k=1;
        if(d>0) {
            c++;
        c=c+dd;
        }
 }
    int minimumLengthEncoding(vector<string>& words) {
//["time", "atime", "btime"]
/*vector<string> words;
words.push_back("btime");
words.push_back("atime");
words.push_back("time");*/
        int c=0;
        for(auto& word : words)
        {
            reverse(word.begin(),word.end());
            insert(word,c);
        }
        return c;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值