// Inserts a word into the trie.
 void insert(string word) {
     if(search(word)) return;
     TrieNode* curr = root;
     for(auto c:word) {
         TrieNode* node = curr->subNode(c);
         if(node != nullptr) {
             curr = node;
         }
         else {
             curr->children.push_back(new TrieNode(c));
             curr->numChildren++;
             curr = curr->subNode(c);
         }
     }
     curr->isend = true;
 }
 // Returns if there is any word in the trie
 // that starts with the given prefix.
 bool startsWith(string prefix) {
     TrieNode* node = root;
     for(auto c:prefix) {
         node = node->subNode(c);
         if(node == nullptr) return false;
     }
     return true;
 }
 // Returns if the word is in the trie.
 bool search(string word) {
     TrieNode* node = root;
     for(auto c:word) {
         node = node->subNode(c);
         if(node == nullptr) return false;
     }
     return node->isend;
 }
Exemple #4
0
bool Trie::startsWith(string prefix)
{
	TrieNode* curr = root;
	for (auto ch : prefix) {
		curr = curr->subNode(ch);
		if (curr == nullptr)
			return false;
	}
	return true;
}
Exemple #5
0
bool Trie::search(string key)
{
	TrieNode* curr = root;
	for (auto ch : key) {
		curr = curr->subNode(ch);
		if (curr == nullptr)
			return false;
	}
	return curr->isend == true;
}
Exemple #6
0
void Trie::insert(string s)
{
	if (search(s)) return;
	TrieNode* curr = root;
	for (auto ch : s) {
		TrieNode* child = curr->subNode(ch);
		if (child != nullptr) {
			curr = child;
		} else {
			TrieNode *newNode = new TrieNode(ch);
			curr->children.push_back(newNode);
			curr = newNode;
		}
		++curr->shared;
	}
	curr->isend = true;
}