定義
字典樹,又稱爲單詞查找樹,Tire數,是一種樹形結構,它是一種哈希樹的變種。用於保存大量的字符串。它的優點是:利用字符串的公共前綴來節約存儲空間。
字典樹結構對應的Java源碼
public class Trie {
char val;
boolean isEnd = false;
Trie[] subChildren = new Trie[26];
public Trie(char val) {
this.val = val;
}
}
字典樹增刪改查對應的Java源碼
本次示例僅展示了insert,find方法
public class TrieDemo {
Trie root = new Trie(' ');
public void insert(String word) {
Trie node = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
int idx = c - 65;
if (node.subChildren[idx] == null) {
Trie sub = new Trie(c);
node.subChildren[idx] = sub;
}
node = node.subChildren[idx];
}
node.isEnd = true;
}
public boolean exist(String word) {
Trie node = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
int idx = c - 65;
if (node.subChildren[idx] == null) {
return false;
}
node=node.subChildren[idx];
}
return node.isEnd;
}
public static void main(String[] args) {
TrieDemo demo = new TrieDemo();
demo.insert("HELLO");
System.out.println(demo.root);
boolean f = demo.exist("HELLO");
System.out.println(f);
}
}
字典樹增刪改查線程安全版本對應的Java源碼
public class TrieSynchronizedDemo {
Trie root = new Trie(' ');
public void insert(String word) {
Trie node = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
int idx = c - 65;
if (node.subChildren[idx] == null) {
synchronized (node) {
if (node.subChildren[idx] == null) {
Trie sub = new Trie(c);
node.subChildren[idx] = sub;
}
}
}
node = node.subChildren[idx];
}
node.isEnd = true;
}
public boolean exist(String word) {
Trie node = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
int idx = c - 65;
if (node.subChildren[idx] == null) {
return false;
}
node = node.subChildren[idx];
}
return node.isEnd;
}
public static void main(String[] args) {
TrieSynchronizedDemo demo = new TrieSynchronizedDemo();
demo.insert("HELLO");
System.out.println(demo.root);
boolean f = demo.exist("HELLO");
System.out.println(f);
}
}