コード例 #1
0
	// Inserts a word into the trie.
	void insert(string s) 
	{
		if (s.empty())
			return;

		TrieNode* p = root;

		int i = 0;
		while (i < s.size())
		{
			TrieNode* tmp = p->findCh(s[i]);
			if (nullptr == tmp)
			{
				p->addChild(s[i]);
				++i;
				p = p->getLastChild();
			}
			else
			{
				++i;
				p = tmp;
			}
		}

		p->isAWord(true);

		return;
	}
コード例 #2
0
	// Returns if there is any word in the trie
	// that starts with the given prefix.
	bool startsWith(string prefix) 
	{
		if (prefix.empty() || " " == prefix)
			return true;

		TrieNode* p = root;

		int i = 0;
		while (nullptr != p && i < prefix.size())
		{
			p = p->findCh(prefix[i++]);
		}

		if (nullptr == p && i <= prefix.size())
			return false;
		else if (nullptr != p && i == prefix.size())
			return true;

	}
コード例 #3
0
	// Returns if the word is in the trie.
	bool search(string key) 
	{
		if (key.empty() || " " == key)
			return true;

		TrieNode* p = root;

		int i = 0;
		while (nullptr != p && i < key.size())
		{
			p = p->findCh(key[i++]);
		}

		if (nullptr == p)
			return false;
		else if (i == key.size() && p->isAWord())
			return true;

		return false;

	}