https://leetcode.com/problems/implement-trie-prefix-tree/
image.png
字典树的实现
talk is cheap ,直接上code
class Trie {
public TrieNode root;
class TrieNode {
public TrieNode() {
isWord = false;
children = new TrieNode[26];
}
public boolean isWord = false;
TrieNode[] children;
}
/**
* Initialize your data structure here.
*/
public Trie() {
root = new TrieNode();
}
/**
* Inserts a word into the trie.
*/
public void insert(String word) {
TrieNode head = this.root;
for (int i = 0; i < word.length(); i++) {
char tmp = word.charAt(i);
int idx = tmp - 'a';
if (head.children[idx] == null) {
head.children[idx] = new TrieNode();
}
head = head.children[idx];
}
head.isWord = true;
return;
}
/**
* Returns if the word is in the trie.
*/
public boolean search(String word) {
TrieNode res = this.find(word);
return res != null && res.isWord == true;
}
/**
* Returns if there is any word in the trie that starts with the given prefix.
*/
public boolean startsWith(String prefix) {
TrieNode res = this.find(prefix);
return res != null;
}
public TrieNode find(String word) {
TrieNode head = this.root;
for (int i = 0; i < word.length(); i++) {
char tmp = word.charAt(i);
int idx = tmp - 'a';
if (head.children[idx] == null) {
return null;
}
head = head.children[idx];
}
return head;
}
}
参考链接:https://zxi.mytechroad.com/blog/data-structure/leetcode-208-implement-trie-prefix-tree/
网友评论