前缀树 LC208

2021-04-19  本文已影响0人  锦绣拾年

前缀树就是一个拥有26个指针的链表
打算实现C++和python 版本。
C++版本
这里表示26个指针有两种方法
一个拥有26个指针的节点。(26个指针的链表)

Node *next[26];\\然后再初始化方法里赋值
    Node(){
        memset(next, 0, sizeof(next));
        isend=false;
    }

或者

vector<Node*> next =vector<Node*>(26,NULL);//struct里vector成员变量必须初始化完成,不然编译器可能无法区分这是一个成员函数声明还是一个成员变量声明,也就是产生歧义。
//vector<Node*> next
//vector<Node*> next(26,NULL) ↑←  都不可

#include <iostream>
#include <string.h>
#include <vector>
#include <string>
using namespace std;

struct Node{
    //https://blog.csdn.net/qq_32523711/article/details/107798999
    vector<Node*> next =vector<Node*>(26,NULL);//vector成员变量必须在这里初始化完毕    
    // Node *next[26];
    bool isend;
    Node(){
        // memset(next, 0, sizeof(next));
        isend=false;
    }
};
class Trie {
public:
    /** Initialize your data structure here. */
    Node *node;
    Trie() {
        node = new Node();
    }
    
    /** Inserts a word into the trie. */
    void insert(string word) {
               if(word.length()==0)
            return;
        Node *cur = this->node;
        for (int i = 0; i < word.length();i++){
            while(cur->next[word[i]-'a']==nullptr){
                cur->next[word[i] - 'a'] = new Node();
            }
            // if(i==word.length()-1){
            //     cur.isend=true;
            // }
            cur = cur->next[word[i] - 'a'];

        }
        cur->isend=true;
        
    }

    // }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        Node *cur = this->node;
        for(int i=0;i<word.length();i++){
            if(cur->next[word[i]-'a']==nullptr)
                return false;
            cur = cur->next[word[i] - 'a'];
        }
        return cur->isend;

    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        Node *cur = this->node;
        for(int i=0;i<prefix.length();i++){
            if(cur->next[prefix[i]-'a']==nullptr)
                return false;
            cur = cur->next[prefix[i] - 'a'];
        }
        return true;

    }
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */
上一篇 下一篇

猜你喜欢

热点阅读