1. 概述
- 适合于字符串操作。
- 时间复杂度为O(w):w为查询单词的长度。
- 存储结构为,把字符串拆分为字母存储。
- 图示:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ef30ced1e59298ae76f852bd710ab7b2.png)
2. 源码
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();
}
public int getSize() {
return size;
}
public void add(String word) {
Node cur = root;
for (int i = 0; i < word.length(); i++) {
char character = word.charAt(i);
if (cur.next.get(character) == null) {
cur.next.put(character, new Node());
}
cur = cur.next.get(character);
}
if (!cur.isWord) {
size++;
cur.isWord = true;
}
}
public boolean contains(String word) {
Node cur = root;
for (int i = 0; i < word.length(); i++) {
char character = word.charAt(i);
if (cur.next.get(character) == null) {
return false;
}
cur = cur.next.get(character);
}
return cur.isWord;
}
public boolean searchByParttern(String word) {
return match(root, word, 0);
}
private boolean match(Node node, String word, int index) {
if (index == word.length()) {
return node.isWord;
}
char character = word.charAt(index);
if (character != '.') {
if (node.next.get(character) == null) {
return false;
}
return match(node.next.get(character), word, index + 1);
} else {
for (Character item : node.next.keySet()) {
if (match(node.next.get(item), word, index + 1)) {
return true;
}
}
return false;
}
}
public boolean isPrefix(String prefix) {
Node cur = root;
for (int i = 0; i < prefix.length(); i++) {
char character = prefix.charAt(i);
if (cur.next.get(character) == null) {
return false;
}
cur = cur.next.get(character);
}
return true;
}
public static void main(String[] args) {
ArrayList<String> words = new ArrayList<>();
int n = 1_000_000;
Random random = new Random();
for (int i = 0; i < n; i++) {
words.add(getRandomString(random.nextInt(26)));
}
Trie trie = new Trie();
for (String word : words) {
trie.add(word);
}
for (String word : words) {
if (trie.contains(word) == false) {
throw new IllegalArgumentException("Word isn't exist!");
}
}
System.out.println("Test Trie tree is complete!");
}
public static String getRandomString(int length) {
String str = "abcdefghijklmnopqrstuvwxyz";
Random random = new Random();
StringBuffer word = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(26);
word.append(str.charAt(number));
}
return word.toString();
}
}