Trie
- 查询每个条目的时间复杂度与字典中一共多少条目无关,而与查询单词的长度有关,时间复杂度为O(w), w为查询单词的长度。
- 每个节点有26个指向下个节点的指针。
代码示例
import java.util.TreeMap;
public class Trie {
private class Node{
public boolean isWord;
public TreeMap<Character, Node> next;
public Node(boolean isWord){
this.isWord = isWord;
next = new TreeMap<>();
}
public Node(){
this(false);
}
}
private Node root;
private int size;
public Trie(){
root = new Node();
size = 0;
}
int getSize(){
return size;
}
}
添加操作
//向Trie中添加一个字符
public void add(String word){
Node cur = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (cur.next.get(c) == null) {
cur.next.put(c, new Node());
}
cur = cur.next.get(c);
}
if (!cur.isWord) {
cur.isWord = true;
size ++;
}
}
查询操作
//查询单词word是否在Trie中
public boolean contains(String word){
Node cur = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (cur.next.get(c) == null){
return false;
}
cur = cur.next.get(c);
}
return cur.isWord;//即使遍历到最后 也无法证明word存在 要判断isWord字段;
}
//查询是否在Trie中有单词以prefix为前缀
public boolean isPrefix(String prefix){
Node cur = root;
for (int i = 0; i < prefix.length(); i++) {
char c = prefix.charAt(i);
if (cur.next.get(c) == null){
return false;
}
cur = cur.next.get(c);
}
return true;
}
相关题目