仅适用a-z的版本
package com.algorithm.offer;
/**
* Trie树(前缀树、字典树)
* @author Lenovo
*
*/
class TrieNode{
// 假设字符只有a-z
TrieNode[] children = new TrieNode[26];
// 是否是末尾节点
boolean isEnd;
}
public class Trie {
static TrieNode trie;
// 构建一棵Trie树
public Trie() {
trie = new TrieNode();
}
public void insert(String word) {
// 从根节点开始搜索
TrieNode cur = trie;
char[] words = word.toCharArray();
for(int i = 0;i < words.length;i++) {
int idx = words[i] - 'a';
// 说明不存在该节点
if(cur.children[idx] == null) {
TrieNode tmp = new TrieNode();
if(i == words.length - 1) {
tmp.isEnd = true;
}
cur.children[idx] = tmp;
}
cur = cur.children[idx];
}
}
public boolean search(String word) {
TrieNode cur = trie;
char[] words = word.toCharArray();
for(