-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchSuggestionSystem.java
More file actions
61 lines (48 loc) · 1.64 KB
/
SearchSuggestionSystem.java
File metadata and controls
61 lines (48 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package Trie;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;
public class SearchSuggestionSystem {
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
TrieNode root = new TrieNode();
for (String product : products)
insert(root, product);
List<List<String>> results = new ArrayList<>();
for (char c : searchWord.toCharArray()) {
if ((root = root.children[c - 'a']) == null) break;
results.add(root.getTopThree());
}
while (results.size() < searchWord.length())
results.add(new ArrayList<>());
return results;
}
private void insert(TrieNode root, String word) {
for (char c : word.toCharArray()) {
if (root.children[c - 'a'] == null)
root.children[c - 'a'] = new TrieNode();
root = root.children[c - 'a'];
root.addToPQ(word);
}
}
static class TrieNode {
public TrieNode[] children;
public PriorityQueue<String> pq;
public TrieNode() {
children = new TrieNode[26];
pq = new PriorityQueue<>((a, b) -> b.compareTo(a));
}
public void addToPQ(String word) {
pq.add(word);
if (pq.size() > 3)
pq.poll();
}
public List<String> getTopThree() {
List<String> topThree = new ArrayList<>();
while (!pq.isEmpty())
topThree.add(pq.poll());
Collections.reverse(topThree);
return topThree;
}
}
}