单词的压缩编码(字典树)

字典树

基本解释

字典树又名前缀树,也叫Trie,字典树用户存储大量的字符串,相比HashMap的存储,字典树节省了大量的空间。如下图:(截图来自LeetCode)
在这里插入图片描述
可以发现,令字典树的根节点为空,从根节点走到叶子节点,每一条路径都会构成一个单词,比如最左边的路径可以构成单词"to",最右边的路径可以构成单词"inn",当然如果不到根节点,也可以构成一个单词,比如最右边的"in",同时也可以发现"in"是"inn"的前缀,那么,字典树的功能就在这提现出来了,即 字典树可以判断某个字符串是否是给定字符串的前缀/后缀,单词正着插就是前缀,单词倒着插就是后缀。

代码结构
/**
 * 节点信息
 */
class TrieNode {
	char val; //节点中要存储的信息
	TrieNode[] children = new TrieNode[26] //孩子的数量可以根据题意设定,字母即为26个
	
	//构造函数
	public TrieNode() {}
	public TrieNode(char val) {this.val = val;}
}

/**
 * 创建字典树并实现插入方法
 */
class Trie {
	TrieNode root;
	// 构造函数
	public Trie(){root = new TrieNode();}

	public void insert(String word){
		TrieNode cur = root; // 记录当前节点
		for(int i = word.length() - 1; i >= 0; i--){
			int position = word.charAt(i) - 'a'; // 记录该字母在树中的位置
			// 判断该节点是否插入过,如果没有插入,就是一个新单词,如果有,就证明是前缀/后缀部分
			if(cur.children[position] == null){
				cur.children[position] = new TrieNode(word.charAt(i));
			}
			cur = cur.children[position]; // 再判断加上下一个字母后,是否是前缀/后缀部分
		}
	}
}

单词的压缩编码

给定一个单词列表,我们将这个列表编码成一个索引字符串 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 Solution {
    public int minimumLengthEncoding(String[] words) {
        int len = 0;
        Trie trie = new Trie();
        Arrays.sort(words, (s1, s2) -> s2.length() - s1.length());

        for (String word: words){
            len = len + trie.insert(word);
        }

        return len;
    }
}

class Trie {
    TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    public int insert(String word){
        TrieNode cur = root;
        boolean isNew = false; //判断是否是新单词

        for(int i = word.length()-1; i >= 0; i--){
            int position = word.charAt(i) - 'a';
            if(cur.children[position] == null){
                isNew = true;
                cur.children[position] = new TrieNode(word.charAt(i));
            }
            cur = cur.children[position];
        }

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

class TrieNode {
    char val;
    TrieNode[] children = new TrieNode[26]; //有一个节点最多可能有26个孩子

    public TrieNode() {}
    public TrieNode(char val) {this.val = val;}
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值