LeetCode 648. 单词替换(字典树的应用)

1. 问题:

1.1 问题描述:

在英语中,我们有一个叫做 词根(root)的概念,它可以跟着其他一些词组成另一个较长的单词——我们称这个词为 继承词(successor)。例如,词根an,跟随着单词 other(其他),可以形成新的单词 another(另一个)。
现在,给定一个由许多词根组成的词典和一个句子。你需要将句子中的所有继承词用词根替换掉。如果继承词有许多可以形成它的词根,则用最短的词根替换它。
你需要输出替换之后的句子。

1.2 示例:

输入:dict(词典) = ["cat", "bat", "rat"] sentence(句子) = "the cattle was rattled by the battery"
输出:"the cat was rat by the bat"

提示:

输入只包含小写字母。
1 <= dict.length <= 1000
1 <= dict[i].length <= 100
1 <= 句中词语数 <= 1000
1 <= 句中词语长度 <= 1000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/replace-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 思路:

典型的字典树应用。

3. C++代码:

class trie{
private:
    bool isend;
    trie* next[26];
public:
    trie(){
        isend = false;
        for(int i=0;i<26;i++){
            next[i] = NULL;
        }
    }

    void insert(string str){
        trie* node = this;
        int i;
        for(i=0;i<str.size();i++){
            if(node->next[str[i]-'a']==NULL){
                node->next[str[i]-'a'] = new trie();
            }
            node = node->next[str[i]-'a'];
        }
        node->isend = true;
    }

    string search(string str){
        trie* node = this;
        string res;

        int i;
        for(i=0;i<str.size();i++){
            if(node->next[str[i]-'a']==NULL){
                return "";
            }
            else{
                node = node->next[str[i]-'a'];
            }

            res += str[i];
            if(node->isend==true){
                return res;
            }
        }
        return "";
    }
};

class Solution {
public:
    string replaceWords(vector<string>& dict, string sentence) {
        
        string result;
        trie root;

        int i;
        for(i=0;i<dict.size();i++){
            root.insert(dict[i]);
        }

        stringstream s1(sentence);
        string temp;
        while(s1 >> temp){
            if(root.search(temp)!=""){
                result += root.search(temp);
                result += " ";
            }
            else{
                result += temp;
                result += " ";
            }
        }

        result = result.substr(0, result.size()-1);

        return result;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值