【leetcode 字典树(前缀树) C++】648. Replace Words

648. Replace Words

在这里插入图片描述

class TrieNode {
    
    
public:
    bool is_end;
    vector<TrieNode*> children = vector<TrieNode*>(26, nullptr);
    TrieNode() {
    
     is_end = false; }
};


class Solution {
    
    
public:
    TrieNode* root = new TrieNode();
    TrieNode* p;

    void insert(string word) {
    
    
        p = root;
        for(int ii = 0; ii < word.size(); ii++) {
    
    
            if(!p->children[word[ii] - 'a']) p->children[word[ii] - 'a'] = new TrieNode();
            p = p->children[word[ii] - 'a'];
        }
        p->is_end = true;
    }

    string replaceWords(vector<string>& dictionary, string sentence) {
    
    
        for(auto &word : dictionary) insert(word);
        string result = "";
        bool tag = false;
        int start = 0;
        p = root;
        for(int ii = 0; ii < sentence.size(); ii++) {
    
    
            if(sentence[ii] == ' ' || ii == sentence.size() - 1) {
    
    
                result += sentence.substr(start, ii - start + 1);
                start = ii+1;
                p = root;
            }
            else {
    
    
                if(p->children[sentence[ii] - 'a']) {
    
    
                    p = p->children[sentence[ii] - 'a'];
                    if(p->is_end) {
    
    
                        result += sentence.substr(start, ii - start + 1);
                        while(ii < sentence.size() && sentence[ii] != ' ') ii++;
                        start = ii+1;
                        if(start < sentence.size()) result += ' ';
                        p = root;
                    }
                }
                else {
    
    
                    while(ii < sentence.size() && sentence[ii] != ' ') ii++;
                    result += sentence.substr(start, ii - start + 1);
                    start = ii+1;
                    p = root;
                }
            }
        }
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_37454852/article/details/113762814