【C++】力扣hot100错误总结

1、题208:构造前缀树

错误点:为了解决这道题,在内部类中定义了指针数组Node。但是忽略了C++和C语言中,初始化数组的时候并不会清空数组里的内容。这会导致初始化的数组里面全是野指针,而非nullptr。因此在Node的构造函数里应当将Node里的内容全部清除。即 memset(next, 0, sizeof(next));

cpp 复制代码
class Trie {
private:
    class Node{
        public:
        string s;
        Node* next[26];
        Node(string s){
            this->s=s;
            memset(next, 0, sizeof(next)); //!!!
        }
    };
    Node* root;
public:
    Trie() {
        root=new Node("");
    }
    
    void insert(string word) {
        Node* p=root;
        for(int i=0;i<word.length();i++){
            int curIndex=word[i]-'a';
            if((p->next)[curIndex]==nullptr){
                (p->next)[curIndex]=new Node("");
            }
            p=(p->next)[curIndex];
        }
        p->s=word;
    }
    
    bool search(string word) {
        Node* p=root;
        for(int i=0;i<word.length();i++){
            int curIndex=word[i]-'a';
            if((p->next)[curIndex]==nullptr){
                return false;
            }
            p=(p->next)[curIndex];
        }
        if(p->s!=word)return false;
        return true;
    }
    
    bool startsWith(string prefix) {
        Node* p=root;
        for(int i=0;i<prefix.length();i++){
            int curIndex=prefix[i]-'a';
            if((p->next)[curIndex]==nullptr){
                return false;
            }
            p=(p->next)[curIndex];
        }
        return true;
    }
};
相关推荐
唐青枫19 小时前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech1 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf3 天前
C#摸鱼实录——IoC与DI案例详解
c#
clint4563 天前
C++进阶(1)——前景提要
c++
咕白m6253 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
夜悊3 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴3 天前
CMake 021: IF 条件判据详诠
c++·cmake
Artech3 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
_wyt0014 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾4 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器