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)
>著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。
*/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章