-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchSuggestionSystem.java
More file actions
45 lines (32 loc) · 1.26 KB
/
Copy pathSearchSuggestionSystem.java
File metadata and controls
45 lines (32 loc) · 1.26 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
package LeetcodePractice;
import java.util.*;
public class SearchSuggestionSystem {
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
Arrays.sort(products);
List<List<String>> result = new ArrayList<>();
String prefix = "";
for (char c : searchWord.toCharArray()) {
prefix += c;
List<String> suggestions = new ArrayList<>();
int count = 0;
for (String product : products) {
if (product.startsWith(prefix)) {
suggestions.add(product);
count++;
}
if (count == 3) break;
}
result.add(suggestions);
}
return result;
}
public static void main(String[] args) {
SearchSuggestionSystem system = new SearchSuggestionSystem();
String[] products1 = {"mobile","mouse","moneypot","monitor","mousepad"};
String searchWord1 = "mouse";
String[] products2 = {"havana"};
String searchWord2 = "havana";
System.out.println("Output 1: " + system.suggestedProducts(products1, searchWord1));
System.out.println("Output 2: " + system.suggestedProducts(products2, searchWord2));
}
}