208. Implement Trie (Prefix Tree)
Implement a trie with insert
, search
, and startsWith
methods.
题目含义:实现字典树的insert
, search
, 和startsWith
方法
字典树概念参考http://blog.csdn.net/u012501459/article/details/46741267
Trie树的基本性质如下:
- 根节点不包括字符,除根节点外每个节点包括一个字符。
- 从根节点到某一节点,路径上经过的字符连接起来,即为对应的字符串。
- 每个节点的所有子节点包含的字符串各不相同。
本题中的Trie树可以简单实现如下:
Trie树节点数据结构定义如下:
- val表示该节点对应的字符
- 子节点简单用一个数组表示,这样实现比较简单,但比较耗费内存
- isWord标记从根节点到该节点是否表示一个单词,还是另一单词的前缀。
1 class Trie { 2 3 class TrieNode { 4 public char val; 5 public boolean isWord; 6 public TrieNode[] children = new TrieNode[26]; 7 public TrieNode() {} 8 TrieNode(char c){ 9 val = c; 10 } 11 } 12 13 private TrieNode root; 14 /** Initialize your data structure here. */ 15 public Trie() { 16 root = new TrieNode(); 17 root.val = ' '; 18 } 19 20 /** Inserts a word into the trie. */ 21 public void insert(String word) { 22 TrieNode ws = root; 23 for(int i = 0; i < word.length(); i++){ 24 char c = word.charAt(i); 25 if(ws.children[c - 'a'] == null){ 26 ws.children[c - 'a'] = new TrieNode(c); 27 } 28 ws = ws.children[c - 'a']; 29 } 30 ws.isWord = true; 31 } 32 33 /** Returns if the word is in the trie. */ 34 public boolean search(String word) { 35 TrieNode ws = root; 36 for(int i = 0; i < word.length(); i++){ 37 char c = word.charAt(i); 38 if(ws.children[c - 'a'] == null) return false; 39 ws = ws.children[c - 'a']; 40 } 41 return ws.isWord; 42 } 43 44 /** Returns if there is any word in the trie that starts with the given prefix. */ 45 public boolean startsWith(String prefix) { 46 TrieNode ws = root; 47 for(int i = 0; i < prefix.length(); i++){ 48 char c = prefix.charAt(i); 49 if(ws.children[c - 'a'] == null) return false; 50 ws = ws.children[c - 'a']; 51 } 52 return true; 53 } 54 }