LeetCode刷题: 【820】单词的压缩编码(字典树、后缀匹配)(c++ 遍历 map)

1. 题目

在这里插入图片描述

2. 思路

官方题解【1. 后缀记录】【2. 字典树】
其他题解【3. 反转排序】

3. 代码(字典树)

/**
* 字典树结点
*/
class Tree{
    
    
private:
    unordered_map<char, Tree*> node;
public:
    bool add(char c){
    
    
        if(node[c] != 0){
    
    
            return false;
        }
        Tree* t = new Tree();
        node[c] = t;
        return true;
    }

    Tree* get(char c){
    
    
        return node[c];
    }

    int size(){
    
    
        return node.size();
    }
};

class Solution {
    
    
public:
    int minimumLengthEncoding(vector<string>& words) {
    
    
        Tree tree;
        int ans = 1;
        for(string word : words){
    
    
            Tree *temp = &tree; // 当前结点
            int flag = 0;
            for(int i = word.size() - 1; i >= 0; i--){
    
    
                if(temp->add(word[i])){
    
     // 是否存在结点
                    if(temp->size() > 1){
    
    
                        flag = 1; // 不完全覆盖某一支,增加全部长度并加上#
                    }
                }else{
    
    
                    flag--; // 完全覆盖某一支,仅增加额外长度
                }
                temp = temp->get(word[i]); // 移动到下一结点
            }
            ans += word.size() + flag; // 记录长度
        }
        return ans;
    }
};


4. 官方代码(c++ 遍历 map)

class TrieNode{
    
    
    TrieNode* children[26];
public:
    int count;
    TrieNode() {
    
    
        for (int i = 0; i < 26; ++i) children[i] = NULL;
        count = 0;
    }
    TrieNode* get(char c) {
    
    
        if (children[c - 'a'] == NULL) {
    
    
            children[c - 'a'] = new TrieNode();
            count++;
        }
        return children[c - 'a'];
    }
};
class Solution {
    
    
public:
    int minimumLengthEncoding(vector<string>& words) {
    
    
        TrieNode* trie = new TrieNode();
        unordered_map<TrieNode*, int> nodes;

        for (int i = 0; i < (int)words.size(); ++i) {
    
    
            string word = words[i];
            TrieNode* cur = trie;
            for (int j = word.length() - 1; j >= 0; --j)
                cur = cur->get(word[j]);
            nodes[cur] = i; // 记录word最后结点
        }

        int ans = 0;
        for (auto& [node, idx] : nodes) {
    
    
            if (node->count == 0) {
    
    
            	// 如果word的最后一个字母后还有结点
            	// 说明当前word被其他word包含
                ans += words[idx].length() + 1;
            }
        }
        return ans;
    }
};
/**
>作者:LeetCode-Solution
>链接:https://leetcode-cn.com/problems/short-encoding-of->words/solution/dan-ci-de-ya-suo-bian-ma-by-leetcode-solution/
>来源:力扣(LeetCode)
>著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
*/

猜你喜欢

转载自blog.csdn.net/Activity_Time/article/details/105172491