问题
实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
例子
思路
children[0] 存 a, children[1] 存 b, children[2] 存 c… 依次类推。所以存的时候我们用当前字符减去 a ,从而得到相应的 children 下标。
-
方法1
$$$$
统计每个单词出现的次数,代码的话只需要将 flag 改成 int 类型,然后每次插入的时候计数即可。
-
方法2
$$$$
代码
//方法1
class Trie {
class TrieNode {
TrieNode[] children = new TrieNode[26];
//是否以该结点为结尾
boolean flag = false;
public TrieNode(){
}
}
/** Initialize your data structure here. */
TrieNode root = new TrieNode();
public Trie() {
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode cur = root;
for(int i=0; i<word.length(); i++){
//如果字符不在trie树中,新建结点
if(cur.children[word.charAt(i)-'a']==null)
cur.children[word.charAt(i)-'a'] = new TrieNode();
cur = cur.children[word.charAt(i)-'a'];
}
cur.flag = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode cur = root;
for(int i=0; i<word.length(); i++){
if(cur.children[word.charAt(i)-'a']==null) return false;
cur = cur.children[word.charAt(i)-'a'];
}
return cur.flag==true;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode cur = root;
for(int i=0; i<prefix.length(); i++){
if(cur.children[prefix.charAt(i)-'a']==null) return false;
cur = cur.children[prefix.charAt(i)-'a'];
}
return true;
}
}
//方法2