题目
实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
示例:
Trie trie = new Trie();
trie.insert(“apple”); trie.search(“apple”); // 返回 true
trie.search(“app”); // 返回 false trie.startsWith(“app”); // 返回 true
trie.insert(“app”); trie.search(“app”); // 返回 true
说明:你可以假设所有的输入都是由小写字母 a-z 构成的。 保证所有输入均为非空字符串。
解题思路
创建一个结点类,每个结点有26个子结点(26个字母),一个布尔变量,表示该结点是否是某个单词的结尾。
然后完成题目要求即可
代码如下
class Trie {
public class TrieNode{
boolean isWord;
TrieNode[] letters = new TrieNode[26];
}
TrieNode root ;
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
if (word != null) {
char[] chars = word.toCharArray();
TrieNode tmp = root;
for (int i = 0; i < chars.length; i++) {
if(tmp.letters[chars[i]-'a'] == null)
tmp.letters[chars[i]-'a'] = new TrieNode();
tmp = tmp.letters[chars[i]-'a'];
}
tmp.isWord = true;
}
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
if (word != null) {
char[] chars = word.toCharArray();
TrieNode tmp = root;
for (int i = 0; i < chars.length; i++) {
if (tmp.letters[chars[i]-'a'] == null)
return false;
tmp = tmp.letters[chars[i]-'a'];
}
return tmp.isWord;
}
return false;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
char[] chars = prefix.toCharArray();
TrieNode tmp = root;
for (int i = 0; i < chars.length; i++) {
if (tmp.letters[chars[i]-'a'] == null)
return false;
tmp = tmp.letters[chars[i]-'a'];
}
return true;
}
}
提交结果
成功
显示详情
执行用时 : 163 ms, 在Implement Trie (Prefix Tree)的Java提交中击败了88.17% 的用户
内存消耗 : 61.8 MB, 在Implement Trie (Prefix Tree)的Java提交中击败了76.08% 的用户