• 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);
        }
    };
  • 相关阅读:
    Sprite Kit编程指南(1)-深入Sprite Kit
    无线点菜系统01(需求分析)
    【体系结构】转移预测器性能的定量评价
    数据挖掘的常见方法
    hdu1711
    poj3358数论(欧拉定理)
    爬虫提取非结构化数据
    pyDes 实现 Python 版的 DES 对称加密/解密--转
    python2 'str' object has no attribute 'decode'
    vba传递参数类型错误
  • 原文地址:https://www.cnblogs.com/zle1992/p/16332682.html
Copyright © 2020-2023  润新知