1. python
1.1 collections.defaultdict(valueType)的使用
defaultdict means that if a key is not found in the dictionary, then instead of a KeyError being thrown, a new entry is created. The type of this new entry is given by the argument of defaultdict.
For example:
somedict = {}
print(somedict[3]) # KeyError
someddict = defaultdict(int)
print(someddict[3]) # print int(), thus 0
1.2 代码
'''
# collections.defaultdict字典,key是letter即代替了数组中index的作用,在Java中定义为数组,那么还需要indexForChar(letter)来将letter转化为index存入or访问数组index上的元素。value是TrieNode,即java中的Node()
'''
class TrieNode:
def __init__(self):
self.childs = collections.defaultdict(TrieNode)
self.is_word = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
current = self.root
for letter in word:
current = current.childs[letter] # 如果不存在该key(letter),就创建一个entry(key-value pair)
current.is_word = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
current = self.root
for letter in word:
current = current.childs.get(letter, None) # 字典中存在这个letter吗?如果是,继续下一循环,如果否,返回false
if current is None:
return False
return current.is_word
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
current = self.root
for letter in prefix:
current = current.childs.get(letter, None)
if current is None:
return False
return True
trie = Trie()
trie.insert("apple")
trie.search("apple")
trie.search("app")
trie.startsWith("app")
trie.insert("app")
trie.search("app")
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
2. JAVA
使用递归实现insert,search,startsWith
代码
class Trie {
private class Node {
Node[] childs = new Node[26];
boolean isLeaf;
}
private Node root = new Node();
/** Initialize your data structure here. */
public Trie() {
}
/** Inserts a word into the trie. */
public void insert(String word) {
insert(word, root);
}
private void insert(String word, Node root){
if (root == null) return;
if (word.length() == 0) {
root.isLeaf = true;
return;
}
int index = indexForChar(word.charAt(0));//word第一个字符的字符编号(在Node[] childs中的index)
if (root.childs[index] == null) root.childs[index] = new Node();//如node不存在,新建node
insert(word.substring(1), root.childs[index]);
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
return search(word, root);
}
private boolean search(String word, Node root){
if (root == null) return false; //找不到,返回false
if (word.length() == 0) return root.isLeaf; //这个单词存不存在在trie中,取决于最后一个字符的isLeaf属性
int index = indexForChar(word.charAt(0));
return search(word.substring(1), root.childs[index]);
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
return startsWith(prefix, root);
}
private boolean startsWith(String prefix, Node root){
if (root == null) return false; //找不到,返回false
if (prefix.length() == 0) return true;
int index = indexForChar(prefix.charAt(0));
return startsWith(prefix.substring(1), root.childs[index]);
}
private int indexForChar(char c){
return c - 'a';
}
}
/**
* 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);
*/