forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSearchSuggestionsSystem.java
More file actions
27 lines (21 loc) · 893 Bytes
/
SearchSuggestionsSystem.java
File metadata and controls
27 lines (21 loc) · 893 Bytes
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
class Solution {
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
List<List<String>> ans = new ArrayList<>();
TreeMap<String, Integer> map = new TreeMap<>();
Arrays.sort(products);
List<String> productsList = Arrays.asList(products);
for (int i = 0; i < products.length; i++) {
map.put(products[i], i);
}
String key = "";
for (char c : searchWord.toCharArray()) {
key += c;
String ceiling = map.ceilingKey(key);
String floor = map.floorKey(key + "{");
if (ceiling == null || floor == null) break;
ans.add(productsList.subList(map.get(ceiling), Math.min(map.get(ceiling) + 3, map.get(floor) + 1)));
}
while (ans.size() < searchWord.length()) ans.add(new ArrayList<>());
return ans;
}
}