查询单词word是否在Trie中
- 如果Trie中有word,那么word的每个字母,依次都能在Trie的每一行中找到(从Trie的第二行开始算起);
// 查询单词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;
}
对比BSTSet和Trie的速度
- Trie快;
public class Main {
public static void main(String[] args) {
System.out.println("Pride and Prejudice");
ArrayList<String> words = new ArrayList<>();
if(FileOperation.readFile("pride-and-prejudice.txt", words)){
long startTime = System.nanoTime();
BSTSet<String> set = new BSTSet<>();
for(String word: words)
set.add(word);
for(String word: words)
set.contains(word);
long endTime = System.nanoTime();
double time = (endTime - startTime) / 1000000000.0;
System.out.println("Total different words: " + set.getSize());
System.out.println("BSTSet: " + time + " s");
// ---
startTime = System.nanoTime();
Trie trie = new Trie();
for(String word: words)
trie.add(word);
for(String word: words)
trie.contains(word);
endTime = System.nanoTime();
time = (endTime - startTime) / 1000000000.0;
System.out.println("Total different words: " + trie.getSize());
System.out.println("Trie: " + time + " s");
}
}
}
输出:
Pride and Prejudice
Total different words: 6530
BSTSet: 0.1964259 s
Total different words: 6530
Trie: 0.1082529 s