首页 > 其他 > 详细

820. 单词的压缩编码

时间:2020-03-28 22:13:04      阅读:63      评论:0      收藏:0      [点我收藏+]

https://leetcode-cn.com/problems/short-encoding-of-words/

Trie+哈希

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;
        }

        int ans = 0;
        for (auto& [node, idx] : nodes) {
            if (node->count == 0) {
                ans += words[idx].length() + 1;
            }
        }
        return ans;
    }
};

820. 单词的压缩编码

原文:https://www.cnblogs.com/Hunter01/p/12589666.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!