剑指 Offer II 063. 替换单词

题目

力扣

思路一 前缀哈希

把词根用一个集合存下来,再判断句子中每个词的每个前缀是否与词根相同,如果相同就返回前缀,否则返回word。

代码一

class Solution:
    def replaceWords(self, dictionary: List[str], sentence: str) -> str:
        rootset = set(dictionary)
        
        def replace(word):
            for i in range(1,len(word)):
                if(word[:i] in rootset):
                    return word[:i]
            return word
        
        return ' '.join(map(replace,sentence.split()))
class Solution:
    def replaceWords(self, dictionary: List[str], sentence: str) -> str:
        words = sentence.split()
        for i in range(len(words)):
            for dic in dictionary:
                if(words[i][0 : len(dic)] == dic):
                    words[i] = dic
        return ' '.join(words)

思路二 前缀树

初始化字典树对象,变量为bool型isEnd和指针数组型next[26],实现insert和search函数。insert函数把字根插入字典树中。search函数在字典树中查询是否有词根是word的前缀,如果有就返回词根,否则返回word。主函数中,先把dictionary中的字符串插入到字典树中。再遍历sentence,获取每一个单词。如果遍历到空格就意味着上一个单词遍历完毕,就调用字典树的search函数,如果不是最后一个单词还需要添加空格。如果不是空格,就把这个字符添加到字符串tmp中。

代码二

class Trie{
private:
    bool isEnd;
    Trie* next[26];
public:
    Trie(){
        isEnd = false;
        memset(next, 0, sizeof(next));
    }

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

    string search(string word){
        Trie* node = this;
        string prefix = "";
        for(char ch : word){
            if(node -> isEnd) break;
            if(node -> next[ch - 'a'] == nullptr)
                return word;
            prefix += ch;
            node = node -> next[ch - 'a'];
        }
        return prefix;
    }
};

class Solution {
public:
    string replaceWords(vector<string>& dictionary, string sentence) {
        Trie* tree = new Trie();
        for(string root : dictionary)
            tree -> insert(root);
        int n = sentence.size();
        string ans = "", tmp = "";
        for(int i = 0; i <= n; i++){
            if(i < n && sentence[i] != ' '){
                tmp += sentence[i];
            }else{
                if(tmp != ""){
                    ans += tree -> search(tmp);
                    if(i < n) ans += " ";
                }
                tmp = "";
            }
        }
        return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值