• LeetCode_前缀树_648.单词替换


    1.题目

    在英语中,我们有一个叫做 词根 (root) 的概念,可以词根后面添加其他一些词组成另一个较长的单词——我们称这个词为 继承词(successor)。例如,词根 an,跟随着单词 other(其他),可以形成新的单词 another(另一个)。

    现在,给定一个由许多词根组成的词典 dictionary 和一个用空格分隔单词形成的句子 sentence。你需要将句子中的所有继承词用词根替换掉。如果继承词有许多可以形成它的词根,则用最短的词根替换它。

    你需要输出替换之后的句子。

    示例 1:
    输入:dictionary = [“cat”,“bat”,“rat”], sentence = “the cattle was rattled by the battery”
    输出:“the cat was rat by the bat”

    示例 2:
    输入:dictionary = [“a”,“b”,“c”], sentence = “aadsfasf absbs bbab cadsfafs”
    输出:“a a b c”

    提示:
    1 <= dictionary.length <= 1000
    1 <= dictionary[i].length <= 100
    dictionary[i] 仅由小写字母组成。
    1 <= sentence.length <= 106
    sentence 仅由小写字母和空格组成。
    sentence 中单词的总量在范围 [1, 1000] 内。
    sentence 中每个单词的长度在范围 [1, 1000] 内。
    sentence 中单词之间由一个空格隔开。
    sentence 没有前导或尾随空格。

    来源:力扣(LeetCode)
    链接:https://leetcode.cn/problems/replace-words

    2.思路

    (1)排序 & 枚举
    ① 对 dictionary 中的词根按照其长度进行升序排序,方便处理继承词有许多可以形成它的词根的情况;

    ② 以 " " 为分隔符将 sentence 进行拆分,并将拆分后得到的词保存到数组 words 中;

    ③ 遍历数组 words,对于当前词 word:

    • 如果 dictionary 中有它的词根,那么将第一个搜索到的词根(也即长度最短的)+ " " 拼接到 res 中;
    • 如果 dictionary 中没有其词根,那么直接将 word + " " 拼接到 res 中;

    ④ 遍历结束后,直接返回 res.toString().trim() 即可。

    由于本题 dictionary 中的词根数最多为 1000,所以搜索起来不会特别耗时,如果词根数非常大,那么可以将其保存到哈希表中,加快搜索过程。

    (2)前缀树
    思路参考本题官方题解

    用 dictionary 中所有词根构建一颗前缀树,并用特殊符号标记结尾。在搜索前缀树时,只需在前缀树上搜索出一条最短的前缀路径即可。

    3.代码实现(Java)

    //思路1————排序 & 枚举
    class Solution {
        public String replaceWords(List<String> dictionary, String sentence) {
            // 对 dictionary 中的词根按照其长度进行升序排序
            dictionary.sort(Comparator.comparingInt(String::length));
            // res 记录替换之后的句子
            StringBuilder res = new StringBuilder();
            //以 " " 为分隔符将 sentence 进行拆分
            String[] words = sentence.split(" ");
            //遍历 words
            for (String word : words) {
                // flag 标记当前词是否有词根存在于 dictionary 中,默认是 false,表示没有
                boolean flag = false;
                for (String root : dictionary) {
                    if (word.startsWith(root)) {
                        res.append(root).append(" ");
                        flag = true;
                        break;
                    }
                }
                if (!flag) {
                    res.append(word).append(" ");
                }
            }
            return res.toString().trim();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    //思路2————前缀树
    class Solution {
        public String replaceWords(List<String> dictionary, String sentence) {
            Trie trie = new Trie();
            for (String word : dictionary) {
                Trie cur = trie;
                for (int i = 0; i < word.length(); i++) {
                    char c = word.charAt(i);
                    cur.children.putIfAbsent(c, new Trie());
                    cur = cur.children.get(c);
                }
                cur.children.put('#', new Trie());
            }
            String[] words = sentence.split(" ");
            for (int i = 0; i < words.length; i++) {
                words[i] = findRoot(words[i], trie);
            }
            return String.join(" ", words);
        }
    
        private String findRoot(String word, Trie trie) {
            StringBuilder root = new StringBuilder();
            Trie cur = trie;
            for (int i = 0; i < word.length(); i++) {
                char c = word.charAt(i);
                if (cur.children.containsKey('#')) {
                    return root.toString();
                }
                if (!cur.children.containsKey(c)) {
                    return word;
                }
                root.append(c);
                cur = cur.children.get(c);
            }
            return root.toString();
        }
    
        class Trie {
            Map<Character, Trie> children;
    
            public Trie() {
                children = new HashMap<Character, Trie>();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
  • 相关阅读:
    数据结构之-队列实现
    实战指南 | Serverless 架构下的应用开发
    VsCode通过Git History插件查看某个页面的版本修改记录
    Sentry安装配置与使用
    解决nomachine扫描不出ip问题
    2024.4.26力扣每日一题——快照数组
    前端多媒体处理工具——ffmpeg的使用
    CPP_D2
    Python从入门到项目实战————程序逻辑结构
    Linux 两台服务器之间传输文件和文件夹的方法
  • 原文地址:https://blog.csdn.net/weixin_43004044/article/details/128011975