字典树的数组实现
首先构造一个节点的数据结构,然后构造一个树的数据结构。
在构造节点数据结构时注意用child[26]表示其26个可能的子节点,使用isword标记是否是一个单词。
在字典树中,跟节点为空,然后时26的n次方这样的存储空间,后面会用哈希表节省存储空间。
class Trie {
public TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root=new TrieNode();
root.val=' ';
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode temp=root;
for(int i=0;i<word.length();i++){
char c=word.charAt(i);
if(temp.child[c-'a']==null)
temp.child[c-'a']=new TrieNode();
temp=temp.child[c-'a'];
}
temp.isword=true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode temp=root;
for(int i=0;i<word.length();i++){
char c=word.charAt(i);
if(temp.child[c-'a']==null)
return false;
temp=temp.child[c-'a'];
}
return temp.isword;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode temp=root;
for(int i=0;i<prefix.length();i++){
char c=prefix.charAt(i);
if(temp.child[c-'a']==null)
return false;
temp=temp.child[c-'a'];
}
return true;
}
}
class TrieNode{
char val;
boolean isword;
TrieNode child[]=new TrieNode[26];
TrieNode(char ch){
TrieNode node=new TrieNode();
node.val=ch;
}
TrieNode(){}
}
字典树的哈希表实现:
class Trie {
TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root=new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode temp=root;
for(int i=0;i<word.length();i++){
int pos=word.charAt(i)-'a';
if(!temp.child.containsKey(pos))
temp.child.put(pos,new TrieNode());
temp=temp.child.get(pos);
}
temp.isword=true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode temp=root;
for(int i=0;i<word.length();i++){
int pos=word.charAt(i)-'a';
if(!temp.child.containsKey(pos))
return false;
temp=temp.child.get(pos);
}
return temp.isword;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode temp=root;
for(int i=0;i<prefix.length();i++){
int pos=prefix.charAt(i)-'a';
if(!temp.child.containsKey(pos))
return false;
temp=temp.child.get(pos);
}
return true;
}
}
class TrieNode{
public Map<Integer,TrieNode> child;
public boolean isword;
TrieNode(){
child=new HashMap<Integer,TrieNode>();
isword=false;
}
}