Java实现 LeetCode 820 单词的压缩编码(字典树)

快来打我* 2023-05-28 06:48 68阅读 0赞

820. 单词的压缩编码

给定一个单词列表,我们将这个列表编码成一个索引字符串 S 与一个索引列表 A。

例如,如果这个列表是 [“time”, “me”, “bell”],我们就可以将其表示为 S = “time#bell#” 和 indexes = [0, 2, 5]。

对于每一个索引,我们可以通过从字符串 S 中索引的位置开始读取字符串,直到 “#” 结束,来恢复我们之前的单词列表。

那么成功对给定单词列表进行编码的最小字符串长度是多少呢?

示例:

输入: words = [“time”, “me”, “bell”]
输出: 10
说明: S = “time#bell#” , indexes = [0, 2, 5] 。

提示:

1 <= words.length <= 2000
1 <= words[i].length <= 7
每个单词都是小写字母 。

  1. class Solution {
  2. public int minimumLengthEncoding(String[] words) {
  3. int len = 0;
  4. Trie trie = new Trie();
  5. Arrays.sort(words, (s1, s2) -> s2.length() - s1.length());
  6. for (String word: words) {
  7. len += trie.insert(word);
  8. }
  9. return len;
  10. }
  11. }
  12. // 定义tire
  13. class Trie {
  14. TrieNode root;
  15. public Trie() {
  16. root = new TrieNode();
  17. }
  18. public int insert(String word) {
  19. TrieNode cur = root;
  20. boolean isNew = false;
  21. // 倒着插入单词
  22. for (int i = word.length() - 1; i >= 0; i--) {
  23. int c = word.charAt(i) - 'a';
  24. if (cur.children[c] == null) {
  25. isNew = true;
  26. cur.children[c] = new TrieNode();
  27. }
  28. cur = cur.children[c];
  29. }
  30. return isNew? word.length() + 1: 0;
  31. }
  32. }
  33. class TrieNode {
  34. char val;
  35. TrieNode[] children = new TrieNode[26];
  36. public TrieNode() { }
  37. }

发表评论

表情:
评论列表 (有 0 条评论,68人围观)

还没有评论,来说两句吧...

相关阅读