GuilinDev

Lc0208

05 August 2008

208 Implement Trie (Prefix Tree)

题目

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

Example:

1
2
3
4
5
6
7
8
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.

分析

因为只有小写字符,所以用一个大小为26的Trie[]数组来存储所有字符,并用一个标记来记录某个单词是否在前缀树中。

设计前缀树里面的三个方法比较类似,都是将传进来的字符串参数转换成字符数组(不转用charAt()也可以),然后对每个字符进行操作,如果Trie中没有该字符的节点做相应处理,最后移动root索引一步,直至将传进来的字符串中的字符全部处理。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class TrieNode { // 自定义TrieNode类,方便使用
    public TrieNode[] children;
    public boolean isEndOfWord;
    
    public TrieNode() {
        children = new TrieNode[26]; // Assuming lowercase English letters only
        isEndOfWord = false;
    }
}

class Trie {
    private TrieNode root;
    
    public Trie() {
        root = new TrieNode();
    }
    
    public void insert(String word) {
        TrieNode node = root;
        
        for (char ch : word.toCharArray()) {
            int index = ch - 'a';
            if (node.children[index] == null) {
                node.children[index] = new TrieNode();
            }
            // 移动去下一个节点
            node = node.children[index];
        }
        
        node.isEndOfWord = true;
    }
    
    public boolean search(String word) {
        TrieNode node = searchPrefix(word);
        return node != null && node.isEndOfWord;
    }
    
    public boolean startsWith(String prefix) {
        TrieNode node = searchPrefix(prefix);
        return node != null;
    }
    
    // helper 方法
    public TrieNode searchPrefix(String prefix) {
        TrieNode node = root;
        
        for (char ch : prefix.toCharArray()) {
            int index = ch - 'a';
            // prefix还有,但node不够用了
            if (node.children[index] == null) {
                return null;
            }
            // 移动去下一个节点
            node = node.children[index];
        }
        
        return node;
    }
}

/**
 * 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);
 */