0
Follow
0
View

I want to know if the index position of the TrieNode array is empty. If it is empty, it creates the node, but now this comparison will cause an error. Let me tell you

asdw7540522 注册会员
2023-02-26 15:08

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;
}


gnlchenyiran 注册会员
2023-02-26 15:08

The following answers are quoted from GPT-3 model, please use them wisely:

// 首先,你可以先在建立TrieNode时,将nexts改为vector<TrieNode*>
// 然后,改写你的insert函数,代码可以参考如下:

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.size() <= index || node.nexts[index] == NULL) {    // 判断当前的位置是否为空,若为空则新建结点
            node.nexts[index] = new TrieNode();
        }
        node = node.nexts[index];
        node.pass++;
    }
    node.end++;
}

Please accept my answer if it answers your question

About the Author

Question Info

Publish Time
2023-02-26 15:08
Update Time
2023-02-26 15:08