LeetCode-最短的单词编码-题解[字典树]

「这是我参与11月更文挑战的第19天,活动详情查看:2021最后一次更文挑战

题目要求

题目描述

单词数组 words 的 有效编码 由任意助记字符串 s 和下标数组 indices 组成,且满足:

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

示例

示例 1

输入: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#"
复制代码

示例 2

输入:words = ["t"]
输出:2
解释:一组有效编码为 s = "t#" 和 indices = [0] 。
复制代码

提示

  • 1 <= words.length <= 2000
  • 1 <= words[i].length <= 7
  • words[i] 仅由小写字母组成

解题思路

有题意可知,如果单词a是单词b的后缀的话,则我们在编码时,可以将单词a忽略掉,因为编码单词b的时候可以同时编码单词a。因此我们只需遍历words列表,判断其他单词是否是当前遍历的单词的后缀,若是,则将单词从words中移除。

为了判断不同的单词是否具有相同的后缀,我们可以将单词倒序放在字典数中,例如,我们有单词‘test’,‘est’,则可以将‘tset’,‘tse’插入树中。之后字典数的叶子节点就代表没有后缀的单词,将单词长度相加,再加上单词个数,即为我们所求的结果。

代码

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;
    }
};
复制代码

猜你喜欢

转载自juejin.im/post/7032969426328780837