题目地址
我的思路
虽然能够解决问题,但是,细细分析,我们发现该方法没有将节点抽象出来,而是把节点直接当作一颗前缀树,这一方面耗费大量内存,另一方面我们错误的把前缀树的子树也当作前缀树,这是错误的逻辑,也是不应该的,我的思路不能解决该问题。
public class Trie {
private Trie[] child;
private boolean end;
public static final int R = 26;
/** Initialize your data structure here. */
public Trie() {
child = new Trie[Trie.R];
end = false;
}
/** Inserts a word into the trie. */
public void insert(String word) {
int i = 0;
Trie t = this;
while(i < word.length() && t.child[word.charAt(i) - 'a'] != null) {
t = t.child[word.charAt(i++) - 'a'];
}
while(i < word.length()) {
t.child[word.charAt(i) - 'a'] = new Trie();;
t = t.child[word.charAt(i++) - 'a'];
}
t.end = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
int i = 0;
Trie t = this;
while(i < word.length() && t.child[word.charAt(i) - 'a'] != null) {
t = t.child[word.charAt(i++) - 'a'];
}
return i >= word.length() && t.end;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
int i = 0;
Trie t = this;
while(i < prefix.length() && t.child[prefix.charAt(i) - 'a'] != null) {
t = t.child[prefix.charAt(i++) - 'a'];
}
return i >= prefix.length();
}
}
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/
更好的思路,把节点抽象出来
import java.util.HashMap;
import java.util.Map;
public class Trie {
private TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode t = root;
for(int i = 0; i < word.length(); i ++) {
char c = word.charAt(i);
if(!t.containsKey(c)) {
t.put(c, new TrieNode());
}
t = t.get(c);
}
t.setEnd();
}
private TrieNode searchPrefix(String word) {
TrieNode t = root;
for(int i = 0; i < word.length(); i ++) {
char c = word.charAt(i);
if(t.containsKey(c)) {
t = t.get(c);
}else {
return null;
}
}
return t;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode t = searchPrefix(word);
return t != null && t.isEnd();
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode t = searchPrefix(prefix);
return t != null;
}
private static class TrieNode{
private TrieNode[] links;
private boolean isEnd;
private static final int R = 26;
public TrieNode() {
links = new TrieNode[TrieNode.R];
}
public boolean containsKey(char key) {
return links[key - 'a'] != null;
}
public TrieNode get(char ch) {
return links[ch - 'a'];
}
public void put(char ch, TrieNode node) {
links[ch - 'a'] = node;
}
public boolean isEnd() {
return isEnd;
}
public void setEnd() {
isEnd = true;
}
}
}
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/