Trie (prefix tree) &(Lc208) Implement Trie (Medium)

  1. Trie介绍:https://www.geeksforgeeks.org/trie-insert-and-search/
  2. 一种树结构,通常用于存储字符,对字符进行预处理 (比如生成dictionary),然后再进行其他判断
  3. 一盘root为空,每个node就是string中的一个character
  4. 每个node有一个field代表其是否是字符串中的最后一个字符:isEndOfWord
  5. 每个node可能有多个子节点:children[]

一个典型TrieNode结构

static class TreeNode {
    TreeNode children[];
    boolean isWord;
    
    public TreeNode() {
        children = new TreeNode[26];
    }
}

  1. Trie与HashTable的对比,可以发现Trie可以解决Prefix这个hashtable无法解决的问题
image.png

Trie的2个基本操作: insert, search

LeetCode 208. Implement Trie (Prefix Tree)

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

Example:

Trie trie = new Trie();

trie.insert("apple");
trie.search("apple");   // returns true
trie.search("app");     // returns false
trie.startsWith("app"); // returns true
trie.insert("app");   
trie.search("app");     // returns true

Note:

  • You may assume that all inputs are consist of lowercase letters a-z.
  • All inputs are guaranteed to be non-empty strings.
class Trie {
    
    static class TrieNode {
        TrieNode children [];
        boolean isEndOfWord;
        
        public TrieNode () {
            children = new TrieNode [26];
        }
    }
    
    private TrieNode root;

    /** Initialize your data structure here. */
    public Trie() {
        root = new TrieNode ();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode node = root;
        
        for (char ch : word.toCharArray ()) {
            if (node.children [ch - 'a'] == null) {
                node.children [ch - 'a'] = new TrieNode ();
            }
            
            node = node.children [ch - 'a'];
        }
        
        node.isEndOfWord = true;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode node = root;
        
        for (char ch : word.toCharArray ()) {
            if (node.children [ch - 'a'] == null) {
                return false;
            }
            
            node = node.children [ch - 'a'];
        }
        
        return node.isEndOfWord;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode node = root;
        
        for (char ch : prefix.toCharArray ()) {
            if (node.children [ch - 'a'] == null) {
                return false;
            }
            
            node = node.children [ch - 'a'];
        }
        
        return true;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */

你可能感兴趣的:(Trie (prefix tree) &(Lc208) Implement Trie (Medium))