208. Implement Trie (Prefix Tree)字典树

Implement a trie with insertsearch,
and startsWith methods.

Note:

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

在Trie树中主要有3个操作,插入、查找和删除。一般情况下Trie树中很少存在删除单独某个结点的情况,因此只考虑删除整棵树。

1、插入

假设存在字符串str,Trie树的根结点为root。i=0,p=root。

1)取str[i],判断p->next[str[i]-97]是否为空,若为空,则建立结点temp,并将p->next[str[i]-97]指向temp,然后p指向temp;

若不为空,则p=p->next[str[i]-97];

2)i++,继续取str[i],循环1)中的操作,直到遇到结束符‘\0‘,此时将当前结点p中的 exist置为true。

2、查找

假设要查找的字符串为str,Trie树的根结点为root,i=0,p=root

1)取str[i],判断判断p->next[str[i]-97]是否为空,若为空,则返回false;若不为空,则p=p->next[str[i]-97],继续取字符。

2)重复1)中的操作直到遇到结束符‘\0‘,若当前结点p不为空并且 exist 为true,则返回true,否则返回false。

3、删除

删除可以以递归的形式进行删除。

class TrieNode {
public:
    // Initialize your data structure here.
    TrieNode *next[26]; //指向子树的指针
    bool exist;
    TrieNode() {
       memset(next, 0, 26*sizeof(TrieNode*));
       exist = false;
    }
};

class Trie {
public:
    Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    void insert(string word) {
       TrieNode* p = root;
       int len = word.size();
       int i =0;
       while(i < len)
       {
           if(p->next[word[i]-'a']==NULL)
           {
               p->next[word[i]-'a'] = new TrieNode;
           }
           p = p->next[word[i]-'a'];
           i++;
       }
       p->exist = true;
    }

    // Returns if the word is in the trie.
    bool search(string word) {
        TrieNode* p = root;
        int len = word.size();
        int i = 0;
        while(i < len)
        {
            p =  p->next[word[i]-'a'];
            if(p==NULL)
             return false;
            else
            {

              i++;
            }
        }
        if(p->exist==true)
         return true;
        else
         return false;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
         TrieNode* p = root;
         int len = prefix.length();
         int i = 0;
         while(i < len)
         {
              p =  p->next[prefix[i]-'a'];
            if(p==NULL)
             return false;
            else
            {

              i++;
            }
         }
         return true;
    }

private:
    TrieNode* root;
};

// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");
时间: 2024-10-15 19:31:29

208. Implement Trie (Prefix Tree)字典树的相关文章

208. Implement Trie (Prefix Tree) -- 键树

Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs are consist of lowercase letters a-z. class TrieNode { public: // Initialize your data structure here. bool isWord; unordered_map<char, TrieNode*> alph

[leedcode 208] Implement Trie (Prefix Tree)

Trie树又被称为字典树.前缀树,是一种用于快速检索的多叉树.Tried树可以利用字符串的公共前缀来节省存储空间. 但如果系统存在大量没有公共前缀的字符串,相应的Trie树将非常消耗内存.(下图为Wiki上的Trie树示意图, https://en.wikipedia.org/wiki/Trie) 子节点用hashMap表示 isWord标记从根节点到该节点是否表示一个单词,还是另一单词的前缀. Implement a trie with insert, search, and startsWi

LeetCode 208. Implement Trie (Prefix Tree)

Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs are consist of lowercase letters a-z. 这道题让我们实现一个重要但又有些复杂的数据结构-字典树, 又称前缀树或单词查找树,详细介绍可以参见网友董的博客,例如,一个保存了8个键的trie结构,"A", "to", "tea&quo

[LeetCode] 208. Implement Trie (Prefix Tree) Java

题目: Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs are consist of lowercase letters a-z. 题意及分析:实现一个字典树或者叫前缀树的插入.删除和startsWith判断.这里定义一个trieNode类作为字典树的节点类.然后有一个chilrden数组保存子节点,一个isWord变量来判断从根节点到该节点是否是一

[leetcode trie]208. Implement Trie (Prefix Tree)

实现一个字典树 1 class Trie(object): 2 3 def __init__(self): 4 self.root = TrieNode() 5 6 def insert(self, word): 7 cur = self.root 8 for i in word: 9 cur = cur.children[i] 10 cur.is_word = True 11 12 13 def search(self, word): 14 cur = self.root 15 for i i

208. Implement Trie (Prefix Tree) 实现前缀树

Implement a trie with insert, search, and startsWith methods. Note: You may assume that all inputs are consist of lowercase letters a-z. var Trie = function() { this.nodes = {}; }; Trie.prototype.insert = function(word) { let node = this.nodes, cur;

Java for LeetCode 208 Implement Trie (Prefix Tree)

Implement a trie with insert, search, and startsWith methods. Note: You may assume that all inputs are consist of lowercase letters a-z. 解题思路: 参考百度百科:Trie树 已经给出了详细的代码: JAVA实现如下: class TrieNode { // Initialize your data structure here. int num;// 有多少单

208. Implement Trie (Prefix Tree)

题目: Implement a trie with insert, search, and startsWith methods. 链接: http://leetcode.com/problems/implement-trie-prefix-tree/ 7/14/201760%,照着课件代码改写的. 将val cast成boolean,注意第21行需要设为false.以下代码可以不需要看,第一版虽然通过了,但是具体内容并不了解. 1 public class Trie { 2 private s

[email&#160;protected] [208] Implement Trie (Prefix Tree)

Trie 树模板 https://leetcode.com/problems/implement-trie-prefix-tree/ class TrieNode { public: char var; bool isWord; TrieNode *next[26]; TrieNode() { var = 0; this->isWord = false; for(auto &c : next) c = NULL; } TrieNode(char c) { var = c; this->