Write based on Monster group and GPT:
The way to create TrieNode arrays is incorrect. Since TrieNode is a class, the new operator is used to dynamically allocate memory. In addition, nexts is a pointer to an array of Trienodes, so it needs to store a pointer of type TrieNode. Therefore, you need to change the type of nexts to TrieNode ** and allocate memory of type TrieNode using the new operator. In this case, you can check that the index position of the TrieNode array is empty by checking whether nexts[index] is NULL, and create the TrieNode if needed.
Here is the modified code:
#include
#include
#include
using namespace std;
class TrieNode;
class TrieNode
{
public:
int pass;
int end;
TrieNode **nexts;
TrieNode()
{
pass = 0;
end = 0;
nexts = new TrieNode *[26]();
}
};
class Trie
{
public:
TrieNode root;
Trie()
{
root = *(new TrieNode);
}
void insert(string str)
{
if (str.size() == 0)
{
return;
}
TrieNode *node = &root;
node->pass++;
int index = 0;
for (int i = 0; i < str.size(); i++)
{
index = str[i] - 'a';
if (node->nexts[index] == NULL)
{
node->nexts[index] = new TrieNode();
}
node = node->nexts[index];
node->pass++;
}
node->end++;
}
};
int main(int argc, char **argv)
{
string a = "abc";
Trie t;
t.insert(a);
return 0;
}