面试算法65:最短的单词编码

题目

输入一个包含n个单词的数组,可以把它们编码成一个字符串和n个下标。例如,单词数组"time","me","bell"可以编码成一个字符串"time#bell#",然后这些单词就可以通过下标0,2,5得到。对于每个下标,都可以从编码得到的字符串中相应的位置开始扫描,直到遇到'#'字符前所经过的子字符串为单词数组中的一个单词。例如,从"time#bell#"下标为2的位置开始扫描,直到遇到'#'前经过子字符串"me"是给定单词数组的第2个单词。给定一个单词数组,请问按照上述规则把这些单词编码之后得到的最短字符串的长度是多少?如果输入的是字符串数组"time","me","bell",那么编码之后最短的字符串是"time#bell#",长度是10。

分析

这个题目的目标是得到最短的编码,因此,如果一个单词A是另一个单词B的后缀,那么单词A在编码字符串中就不需要单独出现,这是因为单词A可以通过在单词B中偏移下标得到。

前缀树是一种常见的数据结构,它能够很方便地表达一个字符串是另一个字符树串的前缀。这个题目是关于字符串的后缀。要把字符串的后缀转换成前缀也比较直观:如果一个字符串A是另一个字符串B的后缀,分别反转字符串A和B得到A'和B',那么A'是B'的前缀。例如,把字符串"me"和"time"反转分别得到"em"和"emit","em"是"emit"的前缀。

解

java 复制代码
public class Test {
    public static void main(String[] args) {
        String[] words = {"time", "me", "bell"};
        System.out.println(minimumLengthEncoding(words));
    }

    static class TrieNode {
        public TrieNode[] children;

        public TrieNode() {
            children = new TrieNode[26];
        }
    }

    public static int minimumLengthEncoding(String[] words) {
        TrieNode root = buildTrie(words);
        int[] total = {0};
        // 初始值为1,是因为每个单词后边有一个#号
        dfs(root, 1, total);
        return total[0];
    }

    private static TrieNode buildTrie(String[] words) {
        TrieNode root = new TrieNode();
        for (String word : words) {
            TrieNode node = root;
            for (int i = word.length() - 1; i >= 0; i--) {
                char ch = word.charAt(i);
                if (node.children[ch - 'a'] == null) {
                    node.children[ch - 'a'] = new TrieNode();
                }

                node = node.children[ch - 'a'];
            }
        }

        return root;
    }

    private static void dfs(TrieNode root, int length, int[] total) {
        boolean isLeaf = true;
        for (TrieNode child : root.children) {
            if (child != null) {
                isLeaf = false;
                dfs(child, length + 1, total);
            }
        }

        if (isLeaf) {
            total[0] += length;
        }
    }
}
相关推荐
淡海水15 分钟前
05-02-源码-Boehm GC标记阶段
算法·unity·c#·游戏引擎·gc
信可维23 分钟前
AI 读 Word 表格总读错?先查合并单元格和表头这 3 处
开发语言·人工智能·c#·word·软件工程
Code_Solitude1 小时前
传智杯备赛代码整理(前4题)
数据结构·算法
怕浪猫1 小时前
3 小时搭一个能用的聊天机器人后端,我用了这套技术栈
后端·面试·github
Jasmine_llq1 小时前
《P8816 [CSP-J 2022] 上升点列》
数据结构·算法·贪心·排序·二维动态规划 dp·类背包状态转移
hetao17338371 小时前
2026-10-19 hetao1733837 的刷题记录
c++·算法
辛苦才能2 小时前
C++ 哈希表深度解析:删除为什么必须打标记,负载因子为什么卡 0.7
开发语言·数据结构·c++·算法
用户84913717547162 小时前
【技术干货】MySQL联合索引底层原理 | 最左前缀原则详解
mysql·面试
m0_639906942 小时前
HashMap:哈希扰动、扩容源码、红黑树转换、并发问题
java·算法·哈希算法
半摆烂日常2 小时前
手机表单的左滑操作:触摸事件的处理细节
大数据·开发语言·人工智能·智能手机·https·c#