我有以下C++代码:
#include <vector>
#include <string>
using namespace std;
struct Trie {
bool eow; //end of word
char val;
vector<Trie> chd; //children
void push_word(const string& word){
Trie& trie = *this;
for (char c: word){
if (trie.chd.empty() || trie.chd.back().val != c) {
trie.chd.push_back(Trie{false, c, vector<Trie>{}});
}
trie = trie.chd.back();
}
trie.eow = true;
}
};
Run Code Online (Sandbox Code Playgroud)
这是弦乐的特里.push_word应该只接受按字典顺序大于trie中已包含的任何单词的字符串; 这样,可以在每个节点上跳过对正确子项的搜索.换句话说,这允许我们从排序的单词向量中有效地构造一个trie:
Trie from_sorted_vector(const vector<string>& words){
Trie trie{false, '\0', vector<Trie>{}};
for (const auto& word: words) {
trie.push_word(word);
}
return trie;
}
Run Code Online (Sandbox Code Playgroud)
我在Rust中有以下内容:
#[derive(Eq, PartialEq, Debug, …Run Code Online (Sandbox Code Playgroud)