【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;
    }
};
相关推荐
我在人间贩卖青春11 分钟前
C++之析构函数
c++·析构函数
我在人间贩卖青春29 分钟前
C++之数据类型的扩展
c++·字符串·数据类型
wangjialelele1 小时前
平衡二叉搜索树:AVL树和红黑树
java·c语言·开发语言·数据结构·c++·算法·深度优先
苏宸啊1 小时前
C++栈和队列
c++
森G1 小时前
七、04ledc-sdk--------makefile有变化
linux·c语言·arm开发·c++·ubuntu
程序员敲代码吗1 小时前
如何通过命令行启动COMSOL的参数化、批处理和集群扫描
java·c#·bash
橘颂TA2 小时前
【测试】高效浏览器操作:基础功能与优化设置大全
c++·功能测试·职场和发展·测试·web测试
一只小小的芙厨2 小时前
寒假集训笔记·以点为对象的树形DP
c++·算法
历程里程碑2 小时前
普通数组----合并区间
java·数据结构·python·算法·leetcode·职场和发展·tornado
艾莉丝努力练剑2 小时前
hixl vs NCCL:昇腾生态通信库的独特优势分析
运维·c++·人工智能·cann