1. 程式人生 > >[LeetCode] 208. Implement Trie (Prefix Tree)

[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:

  1. You may assume that all inputs are consist of lowercase letters a-z.
  2. All inputs are guaranteed to be non-empty strings.

題目大意

實現一個Trie,其中 insert 表示 插入字串 search 表示 查詢字串 startWith 表示 是否有該字串 作為 字首

思路

內建類 node 作為樹的結點。

node 指向 26個node,同時 Boolean isLeaf 標註是 該結點是否為 字串的尾部。

class Trie {

    class Node {
Node[] childs = new Node[26]; boolean isLeaf; } private Node root = new Node(); /** Initialize your data structure here. */ public Trie() { } /** Inserts a word into the trie. */ public void insert(String word) { insert(word,root); } private
void insert(String word, Node node) { if(root == null) return; if(word.length() == 0){ node.isLeaf = true; return; } int index = word.charAt(0) - 'a'; if(node.childs[index] == null) node.childs[index] = new Node(); insert(word.substring(1),node.childs[index]); } /** Returns if the word is in the trie. */ public boolean search(String word) { return search(word,root); } private boolean search(String word, Node node) { if(node == null) return false; if(word.length() == 0) return node.isLeaf; int index = word.charAt(0) - 'a'; return search(word.substring(1),node.childs[index]); } /** Returns if there is any word in the trie that starts with the given prefix. */ public boolean startsWith(String prefix) { return startsWith(prefix,root); } private boolean startsWith(String prefix, Node node) { if(node == null) return false; if(prefix.length() == 0) return true; int index = prefix.charAt(0) - 'a'; return startsWith(prefix.substring(1),node.childs[index]); } } /** * 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); */