C++ 字典树实现


TrieNode.h
Class TrieNode
{
Public:
	 TrieNode() : count(0) {};
	 Int count;
	 Std::map<int,TrieNode*> childNode;
	 ::BlueRiver::Wchar mchar;
};

Class TrieTree
{
Publc:
TrieTree() { root = new TrieNode(); };

Void insert(::BlueRiver::WString word);
Std::vector<::BlueRiver::WString > SearchMatchCommands(::BlueRiver::WString word);

Void AddString(TrieNode* preNode,::BlueRiver::WString word,Std::vector<::BlueRiver::WString >& commands,bool& count);
TrieNode* SearchString(::BlueRiver::WString& word);

Public:
Int GetChangeAscii(int ascii);
Private:
TrieNode* root;
}


TrieNode.cpp
//对大小写字母的ascii进行修改,大小写共占一个节点
//其他位于小写字母后的单字符排列在96号后
Int TrieTree::GetChangeAscii(int ascii)
{
	If(ascii > 96 && ascii < 123)
		Return(ascii - 32);
else if (ascii > 122 && ascii < 127)
	Return(ascii - 26);
	Else
		Return ascii;
}


Void TrieTree::insert(::BlueRiver::WString word)
{
	If(!root || word.empty())
		Return;
	TrieNode* currentNode = root;
	For(::BlueRiver::Wchar str : word)
	{
		Int  siteNum = GetChangeAscii(str);
		Auto iter = currentNode->childNode.find(siteNum - 33);
		//如果不存在,则创建节点
		If(iter == currentNode->childNode.end())
		{
			TrieNode* newNode = new TrieNode();
			newNode->mchar = str;
			currentNode->childNode.insert(make_pair(siteNum - 33, newNode));
			currentNode = newNode;
		}
		Else
			currentNode = iter->second;
	}
	currentNode->count++;
}


TrieNode* TrieTree::SearchString(::BlueRiver::WString& word)
{
	If(!root || word.empty())
		Return  nullptr;
	TrieNode* currentNode = root;
	::BlueRiver::WString noteStr;
	For(auto str : word)
	{
		Int  siteNum = GetChangeAscii(str);
		Auto iter = currentNode->childNode.find(siteNum - 33);

		If(iter != currentNode->childNode.end())
		{
			currentNode = iter->second;
			noteStr = noteStr + currentNode->mchar;
		}
		Else
			Return nullptr;

	}
	Word = noteStr;
	Return currentNode;
}

Void TrieTree::AddString(TrieNode* preNode, ::BlueRiver::WString word, Std::vector<::BlueRiver::WString >& commands, bool& count)
{
	If(count)
		Return;
	For(auto iter = preNode->childNode.begin(); iter != preNode->child.end(); ++iter)
	{
		AddString(iter->second, word + iter->second->mchar, commands, count);
	}
	If(preNode->count != 0)
		Commands.push_back(word);
	//达到10条就退出
	If(commands.size() == 10)
		Count = true;
}

Std::vector<::BlueRiver::WString > TrieTree::SearchMatchCommands(::BlueRiver::WString word)
{
	Std::vector<::BlueRiver::WString > commands;
	::BlueRiver::WString m_word = word;
	TrieNode* m_Node = SearchString(m_word);
	Bool count = false;
	If(m_Node)
		AddString(m_Node, m_word, commands, count);
	Return commands;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值