feat: add tree-finder
This commit is contained in:
parent
1ab711f81c
commit
bdc720694f
5 changed files with 123 additions and 6 deletions
53
lib_vector_search/src/tree_finder.cpp
Normal file
53
lib_vector_search/src/tree_finder.cpp
Normal file
|
@ -0,0 +1,53 @@
|
|||
#include "tree_finder.h"
|
||||
|
||||
void SearchTreeNode::insert(std::string_view partial_word,
|
||||
const string *original_word) {
|
||||
if (partial_word.empty()) {
|
||||
words_.push_front(original_word);
|
||||
} else {
|
||||
children_[partial_word.front()].insert(
|
||||
std::string_view(partial_word).substr(1, partial_word.length()),
|
||||
original_word);
|
||||
}
|
||||
}
|
||||
|
||||
const SearchTreeNode *SearchTreeNode::find(std::string_view search_term) const {
|
||||
if (search_term.empty()) {
|
||||
return this;
|
||||
}
|
||||
|
||||
auto child = children_.find(search_term.front());
|
||||
if (child != children_.cend()) {
|
||||
return child->second.find(search_term.substr(1, search_term.length()));
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::forward_list<const std::string *> SearchTreeNode::words() const {
|
||||
std::forward_list<const std::string *> results(words_);
|
||||
for (const auto &child : children_) {
|
||||
results.merge(child.second.words());
|
||||
}
|
||||
|
||||
return results;
|
||||
};
|
||||
|
||||
SearchTree::SearchTree(const std::vector<std::string> &word_list) {
|
||||
for (const auto &word : word_list) {
|
||||
insert(std::string_view(word), &word);
|
||||
}
|
||||
}
|
||||
|
||||
TreeFinder::TreeFinder(const std::vector<string> &word_list)
|
||||
: search_tree_(word_list) {}
|
||||
|
||||
std::forward_list<const std::string *>
|
||||
TreeFinder::find_prefix(std::string_view search_term) const {
|
||||
const auto *result_node = search_tree_.find(search_term);
|
||||
if (result_node == nullptr) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return result_node->words();
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue