TrieNode为前缀树节点,Trie是前缀树。
Trie中分为几个接口:
getFourNum(),得到IP地址中的4个数字;
addTree(),添加前缀树节点;
searchTree(),在前缀树中进行查找。
struct TrieNode
{
TrieNode()
:nexts{nullptr} {}
int num;
TrieNode *nexts[255];
};
class Trie
{
public:
Trie()
:head(new TrieNode) {}
void addTree(string address)
{
vector<int> nums = getFourNum(address);
TrieNode* cur = head;
for (int i = 0; i < 4; i++)
{
int num = nums[i];
if (cur->nexts[num - 1] == nullptr)
cur->nexts[num - 1] = new TrieNode;
cur = cur->nexts[num - 1];
}
check.insert(address);
}
string searchTree(string Goal_address)
{
vector<int> nums = getFourNum(Goal_address);