前缀树(Trie)
-
前缀树,又称字典树。它是一棵 N 叉树。前缀树一般用于存储、查找字符串。
前缀树的操作
-
运用前缀树可以进行增删查等操作
- 可以利用字符串的公共前缀来减少查询时间,最大限度地减少不必要的字符串比较,查询效率比哈希树高。
-
增
-
public class TrieNode{ public int end; public int pass; public TrieNode[] nexts; public TrieNode(){ this.end = 0; this.pass = 0; this.nexts = new TrieNode[26]; } public static class Trie{ public TireNode root; public Trie(){ root = new TrieNode(); } } public void insert(String word){ if(word ==null){ return; } TrieNode node = root; int index; char[]chars = word.toCharArray(); for(int i = 0;i<chars.length;i++){ index = chars[i] ='a'; if(node.nexts[index] == null){ node.nexts[index] = new TireNode(); } node = node.nexts[index]; node.pass++; } node.end++; } }
-
查询特定的字符串
-
public class TrieNode{ public int end; public int pass; public TrieNode[] nexts; public TrieNode(){ this.end = 0; this.pass = 0; this.nexts = new TrieNode[26]; } public static class Trie{ public TireNode root; public Trie(){ root = new TrieNode(); } } public int search(String word){ if(word == null){ return 0; } TireNode node = root; int index; char[]chars = word.toCharArray(); for(int i = 0;i<chars.length;i++){ index = chars[i] - 'a'; if(node.nexts[index] == null){ return 0; } node = node.nexts[index]; } return node.end; } }
-
查询以......前缀的字符串
-
public class TrieNode{ public int end; public int pass; public TrieNode[] nexts; public TrieNode(){ this.end = 0; this.pass = 0; this.nexts = new TrieNode[26]; } public static class Trie{ public TireNode root; public Trie(){ root = new TrieNode(); } } public int prefixNumber(String preWord){ if(preWord == null){ return 0; } char[]chars = preWord.toCharArray(); TireNode node = root; int index; for(int i = 0;i<chars.length;i++){ index = chars[i] -'a'; if(node.nexts[index] == null){ return 0; } node = node.nexts[index]; } return node.pass; } }
-
删除字符串
-
public class TrieNode{ public int end; public int pass; public TrieNode[] nexts; public TrieNode(){ this.end = 0; this.pass = 0; this.nexts = new TrieNode[26]; } public static class Trie{ public TireNode root; public Trie(){ root = new TrieNode(); } } public void delete(String word){ if(word == null){ return; } char[]chars = word.toCharArray(); int index; TireNode node = root; for(int i = 0;i<chars.length;i++){ index = chars[i]-'a'; if(--node.nexts[index].pass == 0){ return; } node = node.nexts[index]; } node.end--; } }
-