Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
思路分析:这题主要考察Trie 即前缀树的实现,Trie可以用于字典的压缩存储,可以节省空间,但是不节省时间(和HashSet相比)。这题实质是实现一颗多叉树(分支因子26)的插入和查找操作。定义每个TrieNode保存char c,保存一个HashMap用于储存所有的孩子节点,key是对应的字符,value是孩子节点,定义flag hasWord来标记这个node上是否存在word。对于插入操作,直接从上向下分层扫描树,如果没有对应字符节点存在就新建节点,如果有就去相应路径向下探察。对于查询操作,前缀树的定义可以保证当我们从前向后扫描字符串时候,每一个字符都可以从上到下对应前缀树的每一层,所以扫描过程中如果有任何一个字符不存在于当前层中,就可以立刻停止查找返回null,也就是不存在这样的word或者前缀,否则继续从对应的分支向下探察。时间复杂度是O(L),L是树的高度,也就是最长word的长度,空间复杂度26^L,每一层分支因子26,有L层。
AC Code
class TrieNode {
// Initialize your data structure here.
//0908
char c;
HashMap<Character, TrieNode> children = new HashMap<Character, TrieNode>();
boolean hasWord;
public TrieNode(){
}
public TrieNode(char c){
this.c = c;
}
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
public void insert(String word) {
TrieNode cur = root;
HashMap<Character, TrieNode> curChildren = root.children;
char[] wordArray = word.toCharArray();
for(int i = 0; i < wordArray.length; i++){
char wc = wordArray[i];
if(curChildren.containsKey(wc)){
cur = curChildren.get(wc);
} else {
TrieNode newNode = new TrieNode(wc);
curChildren.put(wc, newNode);
cur = newNode;
}
curChildren = cur.children;
if(i == wordArray.length - 1){
cur.hasWord= true;
}
}
}
// Returns if the word is in the trie.
public boolean search(String word) {
if(searchWordNodePos(word) == null){
return false;
} else if(searchWordNodePos(word).hasWord)
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) {
if(searchWordNodePos(prefix) == null){
return false;
} else return true;
}
public TrieNode searchWordNodePos(String s){
HashMap<Character, TrieNode> children = root.children;
TrieNode cur = null;
char[] sArray = s.toCharArray();
for(int i = 0; i < sArray.length; i++){
char c = sArray[i];
if(children.containsKey(c)){
cur = children.get(c);
children = cur.children;
} else{
return null;
}
}
return cur;
}
}
// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
//0918
关于trie的好的博文 http://dongxicheng.org/structure/trietree/