實現一個 Trie,包含 insert, search, 和 startsWith 這三個方法。
樣例 1:
輸入:
insert("lintcode")
search("lint")
startsWith("lint")
輸出:
false
true
樣例 2:
輸入:
insert("lintcode")
search("code")
startsWith("lint")
startsWith("linterror")
insert("linterror")
search("lintcode”)
startsWith("linterror")
輸出:
false
true
false
true
true
題解
Trie(字首樹) 的模板應用.
private TrieNode[] children;
public boolean hasWord;
public TrieNode() {
children = new TrieNode[26];
hasWord = false;
}
public void insert(String word, int index) {
if (index == word.length()) {
this.hasWord = true;
return;
}
int pos = word.charAt(index) - 'a';
if (children[pos] == null) {
children[pos] = new TrieNode();
}
children[pos].insert(word, index + 1);
}
public TrieNode find(String word, int index) {
if (index == word.length()) {
return this;
}
int pos = word.charAt(index) - 'a';
if (children[pos] == null) {
return null;
}
return children[pos].find(word, index + 1);
}
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
root.insert(word, 0);
}
public boolean search(String word) {
TrieNode node = root.find(word, 0);
return (node != null && node.hasWord);
}
public boolean startsWith(String prefix) {
TrieNode node = root.find(prefix, 0);
return node != null;
}
}
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();
}
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;
}
}
}
public boolean search(String word) {
if(searchWordNodePos(word) == null){
return false;
} else if(searchWordNodePos(word).hasWord)
return true;
else return false;
}
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;
}
}