208.实现Trie (前缀树)
Trie(发音类似 “try”)或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。
代码模板如下:
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
| class Trie {
class TireNode { boolean end; TireNode[] children;
public TireNode() { end = false; children = new TireNode[26]; } }
TireNode root;
public Trie() { root = new TireNode(); }
public void insert(String word) { TireNode p = root; for (int i = 0; i < word.length(); i++) { int u = word.charAt(i) - 'a'; if (p.children[u] == null) p.children[u] = new TireNode(); p = p.children[u]; } p.end = true; }
public boolean search(String word) { TireNode p = root; for (int i = 0; i < word.length(); i++) { int u = word.charAt(i) - 'a'; if (p.children[u] == null) return false; p = p.children[u]; } return p.end; }
public boolean startsWith(String prefix) { TireNode p = root; for (int i = 0; i < prefix.length(); i++) { int u = prefix.charAt(i) - 'a'; if (p.children[u] == null) return false; p = p.children[u]; } return true; } }
|