单词的压缩编码

2020-07-08  本文已影响0人  你好宝宝

给定一个单词列表,我们将这个列表编码成一个索引字符串 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] 。

思路:
使用字典树

class TrieNode{
    char val;
    TrieNode[] children=new TrieNode[26];

    public TrieNode(char ch){
        this.val=ch;
    }
}
class Trie{
    TrieNode root;
    public Trie(char ch){
        root=new TrieNode(ch);
    }

    public int insert(String word){
        TrieNode cur=root;
        boolean isNew=false;
        for(int i=word.length()-1;i>=0;i--){
            char ch=word.charAt(i);
            int index=ch-'a';
            if(cur.children[index]!=null){ //若包含这个字符,则进入这个节点
                cur=cur.children[index];
            }else{//否则创建这个节点并进入
                TrieNode newNode=new TrieNode(ch);
                cur.children[index]=newNode;
                cur=cur.children[index];
                isNew=true;
            }
        }
        return isNew ? word.length()+1 : 0; //若是新单词,则返回单词长度加1,否则返回0
    }
}
class Solution {
    public int minimumLengthEncoding(String[] words) {
        int len=0;
        Arrays.sort(words,(s1,s2)->s2.length()-s1.length()); //降序排序
        Trie trie=new Trie('#');
        for(String word : words){
            len +=trie.insert(word);
        }
        return len;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读