leetcode 648. Replace Words 字典树

本文介绍了一种使用字典树(Trie)的数据结构来高效地查找并替换句子中的单词前缀。通过构建字典树,可以在O(m)的时间复杂度内完成单词的插入操作,并能在O(n)的时间复杂度内完成对整个句子中单词的查找和替换,其中m为单词长度,n为句子长度。文章详细解释了字典树节点的设计、单词的插入流程以及查找替换的具体实现。

class Solution {

public:

    typedef struct trie_node{

        int count;

        struct trie_node* next[26];

        bool exist;

    }TrieNode , *Trie;

    TrieNode* CreatTrieNode()

    {

        TrieNode* root=new TrieNode();

        root->count=0;

        memset(root->next, 0, sizeof(root->next));

        root->exist=false;

        return root;

    }

    void insert(TrieNode* root,char *word)

    {

        TrieNode* Node=root;

        while(*word)

        {

            //cout<<*word<<endl;

            char c=*word;

            int id=c-'a';

            if(Node->next[id]==NULL)

                Node->next[id]=CreatTrieNode();

            Node=Node->next[id];

            Node->count++;

            word++;

        }

        Node->exist=true;

    }

    string find_word(TrieNode* root,string word)

    {

        TrieNode* node=root;

        for(int i=0;i<=word.size()-1;i++)

        {

            int id=word[i]-'a';

            //cout<<word[i];

            if(node->exist==true)

                return word.substr(0,i);

            if(node->next[id]==NULL)

                break;

            node=node->next[id];

            

        }

        return word;

    }

    string replaceWords(vector<string>& dict, string sentence) {

        TrieNode* root = CreatTrieNode();

        for(string a:dict)

        {

            char *p=(char*)a.data();

            insert(root, p);

        }

        string res="";

        istringstream is(sentence);

        string n;

        while(is>>n)

        {

            if(!res.empty()) res+=' ';

            res+=find_word(root, n);

        }

        return res;

   }

};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值