【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;
    }
};
相关推荐
whitelbwwww1 小时前
CUDA C++实战--中级
开发语言·前端·c++
ShineWinsu3 小时前
对于Qt:QMessageBox的解析
开发语言·c++·qt·面试·客户端·qmessagebox·消息对话框
小灰灰搞电子7 小时前
C++ initializer_list 详解
c++·list
Rabitebla9 小时前
【Linux】文件篇(六):Shell 实战——从系统调用到命令行重定向
linux·服务器·c++·笔记·学习
Pniubi19 小时前
力扣2 . 两数相加
算法·leetcode·职场和发展
无忧.芙桃1 天前
C++语言原理与实践(二十三):哈希表的实现
c++·链表·哈希算法·散列表·哈希表
文丑颜不良啊1 天前
LeetCode3401~3420题目解析
java·leetcode
AvocadoZeroOneOI1 天前
B4500 [GESP202603 三级] 凯撒密码 详细解题报告
c++·算法
文丑颜不良啊1 天前
LeetCode3421~3440题目解析
java·leetcode
whitelbwwww1 天前
cuBLAS--CUDA高性能线性代数计算库--第一部分
c++·线性代数·gpu算力·cuda c++