【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;
    }
};
相关推荐
ajassi20004 小时前
开源 C++ QT QML 开发(二十三)程序发布
c++·qt·mfc
Tiger_shl4 小时前
三大并发集合ConcurrentDictionary、ConcurrentBag、ConcurrentQueue
开发语言·c#
筱砚.5 小时前
【STL——stack容器】
开发语言·c++
我是华为OD~HR~栗栗呀5 小时前
华为od-22届考研-测试面经
java·c++·python·功能测试·华为od·华为·面试
沐怡旸6 小时前
【穿越Effective C++】条款3:尽可能使用const ——C++不变性的艺术
c++
时光追逐者6 小时前
一个使用 WPF 开发的 Diagram 画板工具(包含流程图FlowChart,思维导图MindEditor)
c#·.net·wpf·流程图
哼?~6 小时前
C++之智能指针
开发语言·c++
mjhcsp6 小时前
C++ long long 类型深度解析:大整数处理的基石
开发语言·c++·策略模式·long long