Trie Service
Trie
Medium
Description
Build tries from a list of <word, freq> pairs. Save top 10 for each node.
Example
Example1
Input:
<"abc", 2>
<"ac", 4>
<"ab", 9>
Output:<a[9,4,2]<b[9,2]<c[2]<>>c[4]<>>>
Explanation:
Root
/
a(9,4,2)
/ \
b(9,2) c(4)
/
c(2)Example2
Solution & Analysis
@xfsm1912:
1.这题是字典树的变形题。其实就是建立字典树结构,同时在每个字符节点上不断向top10=[]这个list中添加给定的frequency。
2.遍历字典树的方法就是之前的传统方法,首先得到当前节点字典children中letter对应的TrieNode()作为child,如果没有letter在这个children里,就返回None,然后把child 定义为TrieNode(),在children中对应letter。然后执行addFrequency()。然后node = child往下移动。
3.在添加frequency时,如果新来的数比之前的数大,就不断交换,直到碰上比它更大的数位置。同时还看看top10长度是不是超过了10
4.时间复杂度是o(len(words))
5.注意,是child添加top10元素
LintCode Official
Last updated
Was this helpful?