Implement a trie with insert, search, and startsWith methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z.
總結Trie:http://www.reibang.com/p/357c1dbe31ec
Solution1:Trie
思路: Basic Trie
Time Complexity: O(word_num * word_len)
Space Complexity: O(number of nodes)
Solution1 Code:
class TrieNode {
public TrieNode[] children = new TrieNode[26];
public boolean isWord;
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode cur = root;
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
if(cur.children[c - 'a'] == null){
cur.children[c - 'a'] = new TrieNode();
}
cur = cur.children[c - 'a'];
}
cur.isWord = true;
}
public boolean search(String word) {
TrieNode cur = root;
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
if(cur.children[c - 'a'] == null) return false;
cur = cur.children[c - 'a'];
}
return cur.isWord;
}
public boolean startsWith(String prefix) {
TrieNode cur = root;
for(int i = 0; i < prefix.length(); i++){
char c = prefix.charAt(i);
if(cur.children[c - 'a'] == null) return false;
cur = cur.children[c - 'a'];
}
return true;
}
}
Solution1.Round1 Code:
class Trie {
class TrieNode {
public TrieNode[] children = new TrieNode[26];;
public boolean is_word;
public char val;
public TrieNode(char c) {
this.val = c;
}
}
private TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode('0');
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode cur = root;
for(int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if(cur.children[c - 'a'] == null) {
cur.children[c - 'a'] = new TrieNode(c);
}
cur = cur.children[c - 'a'];
}
cur.is_word = 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++) {
char c = word.charAt(i);
if(cur.children[c - 'a'] == null) {
return false;
}
cur = cur.children[c - 'a'];
}
return cur.is_word;
}
/** 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++) {
char c = prefix.charAt(i);
if(cur.children[c - 'a'] == null) {
return false;
}
cur = cur.children[c - 'a'];
}
return true;
}
}