走完 c-a 之后呢
同一个词库。运行下面这段程序:
#include <iostream>
#include <map>
#include <string>
using namespace std;
struct Trie {
map<char, Trie*> next; // 往下的分支:每个字符一条
bool end = false; // 走到这里是不是一个完整的词
};
void trie_insert(Trie* t, const string& word) {
Trie* node = t;
for (char ch : word) {
if (node->next.count(ch) == 0) node->next[ch] = new Trie;
node = node->next[ch];
}
node->end = true;
}
int main() {
Trie* t = new Trie;
for (const string& w : {"cat", "car", "card", "dog"}) trie_insert(t, w);
Trie* node = t;
for (char ch : string("ca")) node = node->next[ch];
cout << boolalpha << node->end << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论