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;
}
C++ 字典树实现
于 2021-08-29 17:08:06 首次发布