Skip to content

Instantly share code, notes, and snippets.

@dmthuc
Created December 18, 2018 04:00
Show Gist options
  • Save dmthuc/42442a82cae8ee2a25bfdc171b7fd5dc to your computer and use it in GitHub Desktop.
Save dmthuc/42442a82cae8ee2a25bfdc171b7fd5dc to your computer and use it in GitHub Desktop.
Simple Trie implementation in C++
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <cassert>
using namespace std;
struct Node {
constexpr static char End = '\0';
Node (const char _c)
: c{_c}, childs{}
{}
char c;
map<char, unique_ptr<Node>> childs;
};
void insert(string::const_iterator begin, string::const_iterator end, Node& h) {
if (begin == end)
h.childs.emplace(Node::End, nullptr);
else {
auto p = h.childs.emplace(*begin, make_unique<Node>(*begin));
insert(++begin, end, *(p.first->second));
}
}
bool search(string::const_iterator begin, string::const_iterator end, const Node& h) {
if (begin != end) {
auto it = h.childs.find(*begin);
if (it == h.childs.end())
return false;
else
return search(++begin, end, *(it->second));
} else {
if (h.childs.find(Node::End) != h.childs.end())
return true;
else
return false;
}
}
class Trie {
public:
Trie(vector<string>& input)
:head_{' '}
{
for (const auto& e : input) {
::insert(e.begin(), e.end(), head_);
}
}
void insert(const string& str) {
::insert(str.begin(), str.end(), head_);
}
bool search(const string& str) const {
return ::search(str.begin(), str.end(), head_);
}
private:
Node head_;
};
int main() {
vector<string> input {"word1", "hello", "thank you"};
Trie trie(input);
cout<<trie.search("hello")<<'\n';
cout<<trie.search("hell")<<'\n';
assert(trie.search("word11") == false);
assert(trie.search("word") == false);
cout<<trie.search("thank you")<<'\n';
cout<<trie.search("lamda express")<<'\n';
trie.insert("lamda express");
cout<<trie.search("lamda express")<<'\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment