leetcode笔记:Implement Trie (Prefix Tree)

来源:互联网 发布:手机金山数据恢复大师 编辑:程序博客网 时间:2024/06/06 12:49

一. 题目描述

Implement a trie with insert, search, and startsWith methods.

Note:

You may assume that all inputs are consist of lowercase letters a-z.

二. 题目分析

题目大意很简单,就是实现字典树,其中包括插入、查找和前缀查找三个方法。可以假设所有的输入只包含小写字母a-z。

本题考查字典树数据结构的基础知识。需要先定义TrieNode数据结构,TrieNode为字典树的节点,包含属性val、children和isWord。

其中val表示当前节点所存储的字符;children存储了当前节点的所有子节点的指针;isWord为布尔值,表示当前节点是否存储了一个单词。

Trie树的基本性质有以下几点:

  1. 根节点不包括字符,除根节点外,每个节点存储一个字符;
  2. 从根节点出发,经过一系列子节点,路径上经过的字符连接起来即为对应的字符串。

程序设计时,一个节点的子节点最多有26个,对应26个小写字母,因此简单用一个数组表示。

同时,在leetcode提供的函数基础上,增加了析构函数,因此涉及到new/delete操作。

三. 示例代码

class TrieNode {public:    // Initialize your data structure here.    char val;    bool isWord;    TrieNode* children[26];    // root node    TrieNode(): val(0), isWord(false) {        memset(children, 0x0, sizeof(TrieNode*) * 26);    }    // child node    TrieNode(char c): val(c), isWord(false) {        memset(children, 0x0, sizeof(TrieNode*) * 26);    }};class Trie {public:    Trie() {        root = new TrieNode();    }    // Inserts a word into the trie.    void insert(string word) {        int n = word.length();        if (n == 0) return;        TrieNode* p = root;        for (int i = 0; i < n; ++i)        {            char c = word[i];            if (p->children[c - 'a'] == 0)                p->children[c - 'a'] = new TrieNode(c);            p = p->children[c - 'a'];        }        p->isWord = true;    }    // Returns if the word is in the trie.    bool search(string word) {        int n = word.length();        if (n == 0) return true;        TrieNode *p = root;        for (int i = 0; i < n; ++i)        {            char c = word[i];            p = p->children[c - 'a'];            if (p == NULL) return false;        }        return p->isWord;    }    // Returns if there is any word in the trie    // that starts with the given prefix.    bool startsWith(string prefix) {        TrieNode *p = root;        int n = prefix.length();        if (n == 0) return true;        for (int i = 0; i < n; ++i)        {            char c = prefix[i];            p = p->children[c - 'a'];            if (p == NULL) return false;        }        return true;    }    // Destructor    ~Trie() {        freeTrieNode(root);    }    void freeTrieNode(TrieNode *p){          if (p == NULL)              return;          for (int i = 0; i < 26; ++i)          {              TrieNode *pChild = p->children[i];              if (pChild != NULL)              {                  freeTrieNode(pChild);              }          }          delete p;      }private:    TrieNode* root;};// Your Trie object will be instantiated and called as such:// Trie trie;// trie.insert("somestring");// trie.search("key");

四. 小结

巩固字典树数据结构。

0 0
原创粉丝点击