前缀树的实现c++

class TrieNode{
    public:
    TrieNode *child[26];//定义一个长度为26的数组(字符的取值为a~z)存放的是TrieNode结点型数据
    bool isword;
    TrieNode():isword(false){
        for(int i=0;i<26;i++){
            child[i]=nullptr;//将每一个结点下的子结点初始化为null
        }
    }
    
};


class Trie {
private:
     TrieNode *root;
public:
   
    Trie() {
        // do intialization if necessary
        root=new TrieNode();//创建根结点
    }

    /*
     * @param word: a word
     * @return: nothing
     */
    void insert(string &word) {
        // write your code here
        TrieNode *ptr=root;
        for(int i=0;i<word.size();i++){
            if(ptr->child[word[i]-'a']==nullptr)
        //当word[i]为'a'时,word[i]-'a'=0,即判断child[0]是否为空。
            ptr->child[word[i]-'a']=new TrieNode();
            ptr=ptr->child[word[i]-'a'];
        }
        ptr->isword=true;
    }

    /*
     * @param word: A string
     * @return: if the word is in the trie.
     */
    bool search(string &word) {
        // write your code here
          if(word.size()<=0)
          return false;
          TrieNode *ptr=root;
          for(int i=0;i<word.size();i++){
              if(ptr->child[word[i]-'a']==nullptr)
              return false;
              ptr=ptr->child[word[i]-'a'];
          }
          return ptr->isword;
    }
    

    /*
     * @param prefix: A string
     * @return: if there is any word in the trie that starts with the given prefix.
     */
    bool startsWith(string &prefix) {
        // write your code here
        if(prefix.size()<=0)
        return false;
        TrieNode *ptr=root;
        for(int i=0;i<prefix.size();i++){
            if(ptr->child[prefix[i]-'a']==nullptr)
            return false;
            ptr=ptr->child[prefix[i]-'a'];
        }
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/whyzw1314520/article/details/88306226
今日推荐