Implement Trie

Implement a trie with insert, search, and startsWith methods.

Notice

You may assume that all inputs are consist of lowercase letters a-z.

Example

insert("lintcode")
search("code")
 >>> false
startsWith("lint")
>>> true
startsWith("linterror")
>>> false
insert("linterror")
search("lintcode)
>>> true
startsWith("linterror")
>>> true

分析:

一个单词就是一棵树下来,每个node有26个字母可做孩子。

注意点:1 用数组表示children 2 TrieNode里定义了所有函数,返回node 3 hasWord在insert里set,在find里不用,因为直接返回了node

除了数组还可以用hashmap

答案:

初始化时cur = root,然后往下loop word.length,最后到达最后一个node。

hashmap实现法

Last updated

Was this helpful?