字典树(前缀数)例题以及模板
先放题目
- leetcode 208 -基础字典树
https://leetcode.com/problems/implement-trie-prefix-tree/ - leetcode 211-字典树模糊匹配
https://leetcode.com/problems/add-and-search-word-data-structure-design/description/ - leetcode 212-二维数值字典树(bfs)
https://leetcode.com/problems/word-search-ii/description/
解析
网上字典树的原理和解析很多,就不做太多分析和讲解了,直接上题简易模板。题型变化基于模板修改就可以。
- 字典树的结构
class TrieNode {
public char val;
public boolean isWord;
public TrieNode[] children = new TrieNode[26];
public TrieNode() {}
TrieNode(char c){
TrieNode node = new TrieNode();
node.val = c;
}
}
- 添加 insert(aabccc)
public void insert(String word) {
TrieNode ws = root;
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
if(ws.children[c - 'a'] == null){
ws.children[c - 'a'] = new TrieNode(c);
}
ws = ws.children[c - 'a'];
}
ws.isWord = true;
}
- 全匹配搜索 search(aabccc)->true
public boolean search(String word) {
TrieNode ws = root;
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
if(ws.children[c - 'a'] == null) return false;
ws = ws.children[c - 'a'];
}
return ws.isWord;
}
- 前缀搜索 startsWith(aabc)->true
public boolean startsWith(String prefix) {
TrieNode ws = root;
for(int i = 0; i < prefix.length(); i++){
char c = prefix.charAt(i);
if(ws.children[c - 'a'] == null) return false;
ws = ws.children[c - 'a'];
}
return true;
}
模糊匹配 fuzzySearch(.abc..)->true
public boolean fuzzySearch(String word) { return search(word.toCharArray(), 0, root); } private boolean fuzzySearch(char[] chars, int index, TrieNode parent){ if (index == chars.length){ if (parent.isLeaf){ return true; } return false; } TrieNode [] childNodes = parent.children; char c = chars[index]; if (c == '.'){ for (int i=0;i<childNodes.length;i++){ TrieNode n = childNodes[i]; if (n !=null){ boolean b = fuzzySearch(chars, index+1, n); if (b){ return true; } } } return false; } TrieNode node = childNodes[c-'a']; if (node == null){ return false; } return search(chars, ++index, node); }