208.实现Trie (前缀树)
Trie(发音类似 “try”)或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。
代码模板如下:
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; } }
|