22 August 2020
LeetCode(1268) -- Search Suggestions System
by Jerry Zhang
Problem
Given an array of strings products and a string searchWord. We want to design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with the searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.
Return list of lists of the suggested products after each character of searchWord is typed.
Example 1:
Input: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"
Output: [
["mobile","moneypot","monitor"],
["mobile","moneypot","monitor"],
["mouse","mousepad"],
["mouse","mousepad"],
["mouse","mousepad"]
]
Explanation: products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"]
After typing m and mo all products match and we show user ["mobile","moneypot","monitor"]
After typing mou, mous and mouse the system suggests ["mouse","mousepad"]
My Solution
结果是错的,目前还不知道错在哪里。
class Solution {
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
Trie root = new Trie();
for (String product : products) {
Trie curr = root;
char[] chars = product.toCharArray();
StringBuilder sb = new StringBuilder();
for (char c : chars) {
if (curr.next[c - 'a'] == null) {
curr.next[c - 'a'] = new Trie();
}
sb.append(c);
curr = curr.next[c - 'a'];
}
curr.word = sb.toString();
}
List<List<String>> res = new ArrayList<>();
char[] chars = searchWord.toCharArray();
Trie curr = root;
for (char c : chars) {
List<String> list = new ArrayList<>();
if (curr.next[c - 'a'] != null) {
list = dfs(list, curr.next[c - 'a']);
curr = curr.next[c - 'a'];
}
res.add(list);
}
return res;
}
private List<String> dfs(List<String> list, Trie node) {
if (node.word != null) {
list.add(node.word);
}
if (list.size() == 3) {
return new ArrayList(list);
}
for (Trie next : node.next) {
if (next != null) {
dfs(list, next);
}
}
return list;
}
class Trie {
Trie[] next = new Trie[26];
String word;
}
}
Discuss
class Solution {
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
List<List<String>> res = 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;
res.add(productsList.subList(map.get(ceiling), Math.min(map.get(ceiling) + 3, map.get(floor) + 1)));
}
while (res.size() < searchWord.length()) res.add(new ArrayList<>());
return res;
}
}