社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
Java非递归版
class Trie {
private class Node{
boolean isTrie;
Map<Character, Node> children = new HashMap<>();
}
private Node root = new Node();
/** Initialize your data structure here. */
public Trie() {
}
/** Inserts a word into the trie. */
public void insert(String word) {
Node node = root;
for(int i=0; i<word.length(); i++){
char c = word.charAt(i);
if(!node.children.containsKey(c)){
node.children.put(c, new Node());
}
node = node.children.get(c);
}
node.isTrie = true;
return;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
Node node = root;
for(int i=0; i<word.length(); i++){
char c = word.charAt(i);
Node temp = node.children.get(c);
if(temp == null)
return false;
node = temp;
}
return node.isTrie;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
Node node = root;
for(int i=0; i<prefix.length(); i++){
char c = prefix.charAt(i);
Node temp = node.children.get(c);
if(temp == null)
return false;
node = temp;
}
return node!=null;
}
}
核心思想:空间换取时间
Trie 树又叫又叫字典树、前缀树、单词查找树,它是一颗多叉查找树。与二叉查找树不同,键不是直接保存在节点中,而是由节点在树中的位置决定。
如果海量数据是字符串数据,那么就可以用很小的空间开销构建一颗 Trie 树,空间开销和树高有关。
{“a”, “to”, “tea”, “ted”, “ten”, “i”, “in”, “inn”}
基本性质:
优点
缺点
主要应用:字符串检索、词频统计、字符串排序、前缀匹配等
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!