208. Implement Trie (Prefix Tree)
Solution
主要是要想到那個Node的資料結構。其餘就會很直覺了。
class Node{
public char val;
public boolean isWord;
public Node[] nextOne = new Node[26];
public Node(char c){
this.val = c;
}
}
class Trie {
/** Initialize your data structure here. */
private Node root;
public Trie() {
root = new Node(' ');
}
/** Inserts a word into the trie. */
public void insert(String word) {
Node it = root;
for(char c : word.toCharArray()){
if(it.nextOne[c-'a'] == null){
it.nextOne[c-'a'] = new Node(c);
}
it = it.nextOne[c-'a'];
}
it.isWord = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
Node it = root;
for(char c : word.toCharArray()){
if(it.nextOne[c-'a'] == null){
return false;
}
it = it.nextOne[c-'a'];
}
return it.isWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
Node it = root;
for(char c : prefix.toCharArray()){
if(it.nextOne[c-'a'] == null){
return false;
}
it = it.nextOne[c-'a'];
}
return true;
}
}
Previous211. Design Add and Search Words Data StructureNext421. Maximum XOR of Two Numbers in an Array
Last updated
Was this helpful?