【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;
    }
};
相关推荐
Ray Liang27 分钟前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
肆忆_1 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星1 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
Scout-leaf3 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530143 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
端平入洛4 天前
auto有时不auto
c++
mudtools4 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的5 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21885 天前
.NET 本地Db数据库-技术方案选型
windows·c#