648. 单词替换(Trie shortestPrefixOf)

labuladong 题解

难度中等

在英语中,我们有一个叫做 词根(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"
 
复制代码
class Trie {
    std::vector<Trie*> children;
    bool is_end;
public:
    Trie() {
        is_end = false;
        children = std::vector<Trie*>(26);
    }

    void insert(string word) {
        Trie* node = this;
        for(auto ch : word) {
            if (node->children[ch-'a'] == nullptr) {
                node->children[ch-'a'] = new Trie();
            }
            node = node->children[ch-'a'];
        }
        node->is_end = true;
    }

    std::string shortestPrefixOf(std::string word) {
        // 在树中找到第一个 is_end 节点。就是答案,如果没找到,答案为空
        Trie* node = this;
        std::string res = "";
        for(auto ch : word) {
            if (node->children[ch-'a'] == nullptr) {
                return "";
            }
            res += ch;
            node = node->children[ch - 'a'];
            if (node->is_end) return res;
        }
        return "";
    }
};


class Solution {
public:
    string replaceWords(vector<string>& dictionary, string sentence) {
        stringstream ss;
        ss<<sentence;
        string str;
        string ans;
        Trie *root=new Trie();
        for(string &temp:dictionary)root->insert(temp);
        while(ss>>str){
            string res=root->shortestPrefixOf(str);
            if(res.size())ans+=res;
            else ans+=str;
            ans+=' ';
        }
        return ans.substr(0,ans.size()-1);
    }
};
复制代码

 

 

posted @   乐乐章  阅读(31)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
点击右上角即可分享
微信分享提示