用map实现树的查找
/**
* Initialize your data structure here.
*/
var Trie = function() {
this.cache = {}
};
Trie.prototype.insert = function(word) {
let hash = this.cache
for(let i of word) {
!hash[i] && (hash[i] = {});
hash = hash[i]
}
hash.finish = 1;
};
Trie.prototype.find = function(word) {
let hash = this.cache
for(let i of word) {
if (!hash[i]) return false;
hash = hash[i]
}
return hash
}
Trie.prototype.search = function(word) {
let hash = this.find(word)
return hash && hash.finish !== undefined
};
Trie.prototype.startsWith = function(prefix) {
return this.find(prefix) !== false;
};
时间复杂度
空间复杂度