Leetcode百题斩-字典树
208. Implement Trie (Prefix Tree)[medium]
做完了哈希,来看看数据结构,做做字典树。字典树在搜索方面的作用还是蛮大的,主要是能实现前缀联想以及正确性匹配相关的功能。
字典树又名前缀树,顾名思义就是维护字符串的前缀。这个数据结构难度不大,除了根节点外,每个节点维护当前字符串当前字符的后一个可能出现的字符集合,即每个节点对应了一堆字符串公共前缀,由于字母一共只有26个,因此可以用一个26位的递归数组来表示,下一个字母对应的前缀。然后再加一个字段用来区分当前节点是否为字符串结尾。
该数据结构仅做了解,并且在前缀相关操作时注意进行应用,其可以在 的复杂度下完成搜索插入以及前缀匹配等各种操作
class Trie {private Boolean isEnd;private Trie[] children;public Trie() {isEnd = false;children = new Trie[26];}public void insert(String word) {Trie node = this;for (int i = 0; i < word.length(); i++) {char ch = word.charAt(i);int index = ch - 'a';if (node.children[index] == null) {node.children[index] = new Trie();}node = node.children[index];}node.isEnd = true;}public boolean search(String word) {return this.searchTree(word, true);}public boolean startsWith(String prefix) {return this.searchTree(prefix, false);}private boolean searchTree(String prefix, boolean needEnd) {Trie node = this;for (int i = 0; i < prefix.length(); i++) {char ch = prefix.charAt(i);int index = ch - 'a';if (node.children[index] == null) {return false;}node = node.children[index];}return needEnd ? node.isEnd : true;}
}/*** Your Trie object will be instantiated and called as such:* Trie obj = new Trie();* obj.insert(word);* boolean param_2 = obj.search(word);* boolean param_3 = obj.startsWith(prefix);*/