<p>In English, we have a concept called <strong>root</strong>, which can be followed by some other word to form another longer word - let&#39;s call this word <strong>derivative</strong>. For example, when the <strong>root</strong> <code>&quot;help&quot;</code> is followed by the word <code>&quot;ful&quot;</code>, we can form a derivative <code>&quot;helpful&quot;</code>.</p>

<p>Given a <code>dictionary</code> consisting of many <strong>roots</strong> and a <code>sentence</code> consisting of words separated by spaces, replace all the derivatives in the sentence with the <strong>root</strong> forming it. If a derivative can be replaced by more than one <strong>root</strong>, replace it with the <strong>root</strong> that has <strong>the shortest length</strong>.</p>

<p>Return <em>the <code>sentence</code></em> after the replacement.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> dictionary = [&quot;cat&quot;,&quot;bat&quot;,&quot;rat&quot;], sentence = &quot;the cattle was rattled by the battery&quot;
<strong>Output:</strong> &quot;the cat was rat by the bat&quot;
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> dictionary = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;], sentence = &quot;aadsfasf absbs bbab cadsfafs&quot;
<strong>Output:</strong> &quot;a a b c&quot;
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= dictionary.length &lt;= 1000</code></li>
	<li><code>1 &lt;= dictionary[i].length &lt;= 100</code></li>
	<li><code>dictionary[i]</code> consists of only lower-case letters.</li>
	<li><code>1 &lt;= sentence.length &lt;= 10<sup>6</sup></code></li>
	<li><code>sentence</code> consists of only lower-case letters and spaces.</li>
	<li>The number of words in <code>sentence</code> is in the range <code>[1, 1000]</code></li>
	<li>The length of each word in <code>sentence</code> is in the range <code>[1, 1000]</code></li>
	<li>Every two consecutive words in <code>sentence</code> will be separated by exactly one space.</li>
	<li><code>sentence</code> does not have leading or trailing spaces.</li>
</ul>

class Solution {
public:
    class TrieNode {
    public:
        TrieNode* children[26];
        bool isEndOfWord;
        TrieNode() {
            for (int i = 0; i < 26; ++i) children[i] = nullptr;
            isEndOfWord = false;
        }
    };
    
    class Trie {
    private:
        TrieNode* root;

        bool deleteHelper(TrieNode* node, const string& word, int depth) {
            if (!node) return false;
            if (depth == word.size()) {
                if (!node->isEndOfWord) return false;
                node->isEndOfWord = false;

                for (int i = 0; i < 26; ++i) {
                    if (node->children[i]) return false;
                }
                return true;
            }
            int index = word[depth] - 'a';
            if (deleteHelper(node->children[index], word, depth + 1)) {
                delete node->children[index];
                node->children[index] = nullptr;

                for (int i = 0; i < 26; ++i) {
                    if (node->children[i]) return false;
                }
                return !node->isEndOfWord;
            }
            return false;
        }
        
        TrieNode* searchNode(const string& prefix) {
            TrieNode* node = root;
            for (char c : prefix) {
                int index = c - 'a';
                if (!node->children[index]) return nullptr;
                node = node->children[index];
            }
            return node;
        }

        void collectWords(TrieNode* node, string prefix, vector<string>& words) {
            if (!node) return;
            if (node->isEndOfWord) {
                words.push_back(prefix);
            }
            for (int i = 0; i < 26; ++i) {
                if (node->children[i]) {
                collectWords(node->children[i], prefix + char(i + 'a'), words);
                }
            }
        }

    public:
        Trie() {
            root = new TrieNode();
        }
        void insert(const string& word) {
            TrieNode* node = root;
            for (char c : word) {
                int index = c - 'a';
                if (!node->children[index]) {
                    node->children[index] = new TrieNode();
                }
                node = node->children[index];
            }
            node->isEndOfWord = true;
        }

        vector<string> prefixSearch(const string& prefix) {
            vector<string> words;
            TrieNode* node = searchNode(prefix);
            if (node) {
                collectWords(node, prefix, words);
            }
            return words;
        }

        void deleteWord(const string& word) {
            deleteHelper(root, word, 0);
        }
    };

    string replaceWords(vector<string>& dictionary, string sentence) {
        string result;
        Trie trie;
        int begin = 0;
        sort(dictionary.begin(), dictionary.end());
        for (int i = 1; i <= sentence.size(); i++) {
            if (sentence[i] == ' ' || i == sentence.size()) {
                string word = sentence.substr(begin, i - begin);
                trie.insert(word);
                begin = i + 1;
                bool found = false;
                for (auto j : dictionary) {
                    if (trie.prefixSearch(j).size() > 0) {
                        result += j;
                        found = true;
                        if (i < sentence.size()) {
                            result += ' ';
                        }
                        trie.deleteWord(word);
                        break;
                    }
                }
                if (!found) {
                    result += word;
                    if (i < sentence.size()) {
                        result += ' ';
                    }
                } 
            }
        }
        return result;
    }
};
540917