Leetcode--820:单词的压缩编码(java)

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

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

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

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

思路:

这道题就是求字符串后缀,如果字符串a的后缀包含字符串b,那么b就不用再添加

字典树

先将字符串数组按照长度排序,将字符串长的先添加进去,之后遍历长度短的。

按照逆序将字符串插入字典树,后面的字符串如果可以在字典树之中找到,那么就不用添加这个字符串,反之,将这个字符串也逆序插入字典树

示例:

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

提示:

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

代码:

class Solution {

   public Tree root = new Tree();

    class Tree{

        Tree children[] = new Tree[26];

        char val;

    }

     public int minimumLengthEncoding(String[] words) {

            if(words.length==0){

                return 0;

            }

            Arrays.sort(words, (s1, s2) -> s2.length() - s1.length());

            int count = 0;

            for(int i=0;i<words.length;i++)

            {

                count+=insert(words[i]);

            }

            return count;

        }

     public int insert(String word)

     {

         Tree cur = root;

         boolean isNew = false;

         for(int i=word.length()-1;i>=0;i--)

         {

             int c = word.charAt(i)-'a';

             if(cur.children[c]==null)

             {

                 isNew = true;

                 cur.children[c] = new Tree();

             }

             cur =cur.children[c];

         }

         return isNew?word.length()+1:0;

     }

}

发布了307 篇原创文章 · 获赞 9 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/hx1043116928/article/details/105157633