LeetCode 820. Short Encoding of Words - Java - Trie

36 篇文章 0 订阅
30 篇文章 1 订阅

Given a list of words, we may encode it by writing a reference string S and a list of indexes A.

For example, if the list of words is ["time", "me", "bell"], we can write it as S = "time#bell#" and indexes = [0, 2, 5].

Then for each index, we will recover the word by reading from the reference string from that index until we reach a "#" character.

What is the length of the shortest reference string S possible that encodes the given words?

Example:
Input: words = ["time", "me", "bell"]
Output: 10
Explanation: S = "time#bell#" and indexes = [0, 2, 5].
Note:
  • 1 <= words.length <= 2000.
  • 1 <= words[i].length <= 7.
  • Each word has only lowercase letters.
Java代码
class Solution {
    public int minimumLengthEncoding(String[] words) {
        if (words.length == 1) {
            return words[0].length() + 1;
        }
        // 按照单词长度降序排序
        Arrays.sort(words, (o1, o2) -> {
            int len1 = o1.length();
            int len2 = o2.length();
            return (len1 < len2) ? 1 : ((len1 == len2) ? 0 : -1);
        });
        TrieNode root = new TrieNode();
        int result = 0;
        for (int i = 0; i < words.length; ++i) {
            result += insert(words[i], root);
        }
        return result;
    }

    private int insert(String word, TrieNode root) {
        TrieNode trieNode = root;
        boolean newWord = false;
        char[] chars = word.toCharArray();
        for (int j = chars.length - 1; j >= 0; --j) {
            int v = chars[j] - 'a';
            if (trieNode.children[v] == null) {
                newWord = true;
                trieNode.children[v] = new TrieNode();
            }
            trieNode = trieNode.children[v];
        }
        return newWord ? (chars.length + 1) : 0;
    }

    private class TrieNode {
        TrieNode[] children = new TrieNode[26];
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值