820. 单词的压缩编码

题目描述

单词数组 words 的 有效编码 由任意助记字符串 s 和下标数组 indices 组成,且满足:
words.length == indices.length
助记字符串 s 以 '#' 字符结尾
对于每个下标 indices[i] ,s 的一个从 indices[i] 开始、到下一个 '#' 字符结束(但不包括 '#')的 子字符串 恰好与 words[i] 相等
给你一个单词数组 words ,返回成功对 words 进行编码的最小助记字符串 s 的长度 。

  • 示例
输入:words = ["time", "me", "bell"]
输出:10
解释:一组有效编码为 s = "time#bell#" 和 indices = [0, 2, 5] 。
words[0] = "time" ,s 开始于 indices[0] = 0 到下一个 '#' 结束的子字符串,如加粗部分所示 "time#bell#"
words[1] = "me" ,s 开始于 indices[1] = 2 到下一个 '#' 结束的子字符串,如加粗部分所示 "time#bell#"
words[2] = "bell" ,s 开始于 indices[2] = 5 到下一个 '#' 结束的子字符串,如加粗部分所示 "time#bell#"

解决方案

class TrieNode {
public:
    TrieNode() {
        for (int i=0;i<26;i++) {
            children[i]=nullptr;
        }
        end=false;
    }

    bool containsKey(char ch) {
        return children[ch-'a']!=nullptr;
    }

    void put(char ch, TrieNode*node) {
        children[ch-'a']=node;
    }

    TrieNode* get(char ch) {
        return children[ch-'a'];
    }

    void setEnd(bool flag) {
        end=flag;
    }

    bool isEnd() {
        return end;
    }

private:
    bool end;
    TrieNode *children[26];
};

class Trie {
public:
    Trie() {
        root=new TrieNode();
    }

    TrieNode* insert(string word) {
        TrieNode *node=root;
        for (char ch:word) {
            if (!node->containsKey(ch)) {
                node->put(ch, new TrieNode());
                newNode=true;
            }
            if (node->isEnd()) {
                node->setEnd(false);
            }
            node=node->get(ch);
        }
        if (newNode) {
            node->setEnd(true);
            newNode=false;
        }

        return node;
    }

private:
    bool newNode;
    TrieNode *root;
};

class Solution {
public:
    int minimumLengthEncoding(vector<string>& words) {
        unordered_map<TrieNode*, int> wordMap;
        Trie *trie=new Trie();
        for (int i=0;i<words.size();i++) {
            reverse(words[i].begin(),words[i].end());
            TrieNode* node = trie->insert(words[i]);
            wordMap[node]=i;
        }

        int ans=0;
        for (auto item = wordMap.begin(); item != wordMap.end(); ++item) {
            if (item->first->isEnd()) {
                ans+=words[item->second].length()+1;
            }
        }

        return ans;
    }
};
原文地址:https://www.cnblogs.com/hunter-w/p/15042258.html