一、题目
二、代码
class Trie
{
class Node
{
private boolean isEnd ;
private Node[] next;
public Node()
{
isEnd = false;
next = new Node[26];
}
}
private Node root;
public Trie()
{
root = new Node();
}
public void insert(String word)
{
Node node = root;
for(char i : word.toCharArray())
{
if(node.next[i-'a'] == null)
{
node.next[i-'a'] = new Node();
}
node = node.next[i-'a'];
}
node.isEnd = true;
}
public boolean search(String word)
{
Node node = mySearch(word);
return node!=null && node.isEnd == true;
}
public boolean startsWith(String prefix)
{
Node node = mySearch(prefix);
return node!=null ;
}
public Node mySearch(String word)
{
Node node = root;
for(char i: word.toCharArray())
{
if(node.next[i-'a'] == null)
{
return null;
}
node = node.next[i-'a'];
}
return node;
}
}
三、运行结果