Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
Trie是指前缀树或字典树,是一种有序搜索树,多用于保存键是strings的动态集合。键不是直接保存在节点中,而是由节点在树中的位置决定。一个节点的所有子孙都有相同的前缀,也就是这个节点对应的字符串,而根节点对应空字符串。
class TrieNode {
// Initialize your data structure here.
private char key;
private boolean stop = false;
private List<TrieNode> children;
public TrieNode() {
children = new ArrayList<TrieNode>();
}
public TrieNode(char key){
this.key = key;
children = new ArrayList<TrieNode>();
}
public boolean isStop() {
return stop;
}
public void setStop(boolean stop) {
this.stop = stop;
}
public char getKey() {
return key;
}
public void setKey(char key) {
this.key = key;
}
public List<TrieNode> getChildren() {
return children;
}
public void addChild(TrieNode child) {
this.children.add(child);
}
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
public void insert(String word) {
char[]list = word.toCharArray();
List<TrieNode> temp = root.getChildren();
TrieNode node = null;
TrieNode preNode = root;
int len = list.length;
int i = 0;
for(i = 0; i < len; i++){
node = inList(list[i], temp);
if(node!=null){
temp = node.getChildren();
preNode = node;
}else
break;
}
for(int j = i; j < len; j++){
TrieNode t = new TrieNode(list[j]);
preNode.addChild(t);
preNode = t;
}
preNode.setStop(true);
}
// Returns if the word is in the trie.
public boolean search(String word) {
char[]list = word.toCharArray();
List<TrieNode> temp = root.getChildren();
TrieNode node = null;
for(char c: list){
node = inList(c, temp);
if(node!=null)
temp = node.getChildren();
else
return false;
}
if(node.isStop())
return true;
else
return false;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
char[]list = prefix.toCharArray();
List<TrieNode> temp = root.getChildren();
TrieNode node = null;
for(char c: list){
node = inList(c, temp);
if(node!=null)
temp = node.getChildren();
else
return false;
}
return true;
}
// Return the TrieNode if the char is in the children
// else return null
public TrieNode inList(char c, List<TrieNode> list){
for(TrieNode t:list){
if(c==t.getKey())
return t;
}
return null;
}
}
// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
对于节点的设计是,每个节点保存着一个字符;以及一个用于表示是否有string在此停止的布尔类型stop变量,表示词语的终止;最后是一个列表保存子节点。