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); } };
分类:
LeetCode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性