字典树
字典树是一种很常用的数据结果,用于判断一个单词在不在字典里面,时间复杂度是单词的长度。有次微软实习的笔试题是给10w个网段,问一个ip在不在这些网段里面,也是用字典树可以解决。
字典树的节点定义如下:
public class Node{ private boolean end; private Node[] children; public Node(){ end = false; children = new Node[26]; } }
end表示单词是否完结,children是26个子孩子,从a到z
单词插入:
从根节点往叶子节点走,根据当前的字符得到子孩子的下标,若子孩子为null,则新建一个Node,然后向子孩子走,直到单词遍历完。
单词查询:
从根节点往叶子节点走,根据当前的字符得到子孩子的下标,若子孩子为null,表示单词不在字典里面,否则向子孩子走,遍历完单词之后,返回所在节点的end标记。
代码如下:
public class Tree{ private Node root; public Tree(){ root = new Node(); } public void addWord(String word){ word = word.toLowerCase().trim(); Node p = root; for(int i=0;i<word.length();i++){ int index = word.charAt(i) - 'a'; if(p.children[index]==null){ p.children[index] = new Node(); } p = p.children[index]; } p.end = true; } public boolean isExist(String word){ word = word.toLowerCase().trim(); Node p = root; for(int i=0;i<word.length();i++){ int index = word.charAt(i) - 'a'; if(p.children[index]==null){ return false; } p = p.children[index]; } return p.end; } }

浙公网安备 33010602011771号