int cnt; // 维护当前结点标号,头结点标号为0 int next[MAX_CAPACITY][ALPHABET_SIZE]; bool isEndOfWord[MAX_CAPACITY]; // 标记某结点结尾的字符串是否存在
voidinsert(std::string&s){ // TODO: 插入字符串s到Trie树中 int n = s.length(); int p = 0; for(int i = 0; i < n; i++) { int index = s[i] - 'a'; if(next[p][index] == 0) next[p][index] = ++cnt; p = next[p][index]; } isEndOfWord[p] = true; // 每次插入完成时在这个字符串所代表的节点处打上标记 }
Trie(std::vector<std::string>&words) { // TODO: 构建Trie树 for(auto &word : words) insert(word); } boolfind(std::string&s){ // TODO: 查询字符串s是否在Trie树中 int n = s.length(); int p = 0; for(int i = 0; i < n; i++) { int index = s[i] - 'a'; if(next[p][index] == 0) returnfalse; p = next[p][index]; } return isEndOfWord[p]; } };