Build tries from a list ofpairs. Save top 10 for each node.
<"abc", 2>
<"ac", 4>
<"ab", 9>
Root
/
a(9,4,2)
/ \
b(9,2) c(4)
/
c(2)
public class TrieService {
private TrieNode root = null;
public TrieService() {
root = new TrieNode();
}
public TrieNode getRoot() {
// Return root of trie root, and
// lintcode will print the tree struct.
return root;
}
// @param word a string
// @param frequency an integer
public void insert(String word, int frequency) {
if (word == null || word.isEmpty()) {
return;
}
TrieNode last = root;
for (int i = 0; i < word.length(); i++) {
Character c = word.charAt(i);
TrieNode child = last.children.get(c);
if (child == null) {
child = new TrieNode();
last.children.put(c, child);
}
List<Integer> top10 = child.top10;
top10.add(frequency);
Collections.sort(top10, Collections.reverseOrder());
if (top10.size() > 10) {
top10.remove(top10.size() - 1);
}
last = child;
}
}
}