208. 实现 Trie (前缀树)
作者:互联网
package leetcode; class Trie { private Trie[] children; //当前节点是否为一个单词的结尾 private boolean isEnd; public Trie() { //每个节点最多有26个字母 children=new Trie[26]; isEnd=false; } public void insert(String word) { Trie node=this; for(int i=0;i<word.length();i++) { //找出当前字符的下标 int index=word.charAt(i)-'a'; if(node.children[index]==null) { node.children[index]=new Trie(); } //指向下一个节点 node=node.children[index]; } node.isEnd=true; } //前缀不为空,且为最后一个字符 public boolean search(String word) { Trie node=SearchPrefix(word); return node!=null&&node.isEnd; } public boolean startsWith(String prefix) { Trie node=SearchPrefix(prefix); return node!=null; } //判断是否有前缀 public Trie SearchPrefix(String prefix) { Trie node=this; for(int i=0;i<prefix.length();i++) { int index=prefix.charAt(i)-'a'; if(node.children[index]==null) { return null; } node=node.children[index]; } return node; } }
标签:26,前缀,Trie,208,isEnd,private,public,children 来源: https://www.cnblogs.com/Yshun/p/16276312.html