[Leetcode] 648. Replace Words 解题报告

本文介绍了一种使用字典树(Trie)结构实现的算法,该算法能够在给定的句子中找到并替换由一系列根词汇构成的继承词汇,用最短的根词汇进行替代。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

In English, we have a concept called root, which can be followed by some other words to form another longer word - let's call this word successor. For example, the root an, followed by other, which can form another word another.

Now, given a dictionary consisting of many roots and a sentence. You need to replace all the successor in the sentence with the rootforming it. If a successor has many roots can form it, replace it with the root with the shortest length.

You need to output the sentence after the replacement.

Example 1:

Input: dict = ["cat", "bat", "rat"]
sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"

Note:

  1. The input will only have lower-case letters.
  2. 1 <= dict words number <= 1000
  3. 1 <= sentence words number <= 1000
  4. 1 <= root length <= 100
  5. 1 <= sentence words length <= 1000

思路

又是一道字典树的题目,分为两步:1)将字典中的所有前缀都加入到字典树中。2)对于sentence中的每个单词,我们在字典树中查找是否有它的前缀存在于字典树中,如果有,则用其最小的前缀来代替它;否则就保持不变。最后返回修改后的sentence即可。

代码

class Solution {
public:
    string replaceWords(vector<string>& dict, string sentence) {
        root = new TrieNode();      // step 1: add all the string in dict
        for (auto &s : dict) {
            addTrieNode(s);
        }
        // step 2: replace the s once it has prefix in the Trie
        istringstream iss(sentence);
        string s, ret, prefix;
        while(iss >> s) {
            prefix = search(s);
            ret += prefix == "" ? s : prefix;
            ret += ' ';
        }
        ret.pop_back();
        return ret;
    }
private:
    struct TrieNode {
        bool finished;
        vector<TrieNode*> children;
        TrieNode() {
            finished = false;
            children = vector<TrieNode*>(26, NULL);
        }
    };
    void addTrieNode(string &s) {
        TrieNode *node = root;
        for (int i = 0; i < s.length(); ++i) {
            int index = s[i] - 'a';
            if (node->children[index] == NULL) {
                node->children[index] = new TrieNode();
            }
            node = node->children[index];
        }
        node->finished = true;
    }
    string search(string &s) {
        TrieNode *node = root;
        string ret;
        for (int i = 0; i < s.length(); ++i) {
            int index = s[i] - 'a';
            if (node->children[index] == NULL) {
                return "";
            }
            ret += ('a' + index);
            node = node->children[index];
            if (node->finished == true) {
                return ret;
            }
        }
        return "";
    }
    TrieNode *root;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值