Description
Implement a trie with insert, search, and startsWith methods.
Example:
Trie trie = new Trie();
trie.insert(“apple”);
trie.search(“apple”); // returns true
trie.search(“app”); // returns false
trie.startsWith(“app”); // returns true
trie.insert(“app”);
trie.search(“app”); // returns true
Note:
You may assume that all inputs are consist of lowercase letters a-z.
All inputs are guaranteed to be non-empty strings.
Solution
实现Trie树,也就是前缀?。能够插入单词,寻找单词,以及是否存在前缀。自己设计TrieNode,拥有val记录字符;isword记录是否有单词;children[26]记录孩子。两个构造函数。
For construct funcition, we create an empty root node.
For insert, start iteration at root, for each character in word, if corresponding child is null, create a TrieNode with val of this character. After the iteration, set isWord = true
For search, same to insert, but iteratively return isWord of last character.
For startWith, same, return true if the iteration could complete.
Code
class Trie {
public class TrieNode{
char val;
boolean isWord;
TrieNode[] children = new TrieNode[26];
TrieNode(){}
TrieNode(char c){
TrieNode node = new TrieNode();
node.val = c;
}
}
/** Initialize your data structure here. */
TrieNode root;
public Trie() {
root = new TrieNode();
root.val = ' ';
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode cur = root;
for (int i = 0; i < word.length(); i++){
char ch = word.charAt(i);
if (cur.children[ch - 'a'] == null){
cur.children[ch - 'a'] = new TrieNode(ch);
}
cur = cur.children[ch - 'a'];
}
cur.isWord = 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 ch = word.charAt(i);
if (cur.children[ch - 'a'] == null){
return false;
}
cur = cur.children[ch - 'a'];
}
return cur.isWord;
}
/** 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 ch = prefix.charAt(i);
if (cur.children[ch - 'a'] == null){
return false;
}
cur = cur.children[ch - 'a'];
}
return 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);
*/
Time Complexity: O(n)
Space Complexity: O()