-
Notifications
You must be signed in to change notification settings - Fork 15
/
Problem_5_Search_Suggestions_System.java
85 lines (68 loc) · 2.42 KB
/
Problem_5_Search_Suggestions_System.java
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package Trie;
// Problem Statement: Search Suggestions System (medium)
// LeetCode Question: 1268. Search Suggestions System
import java.util.ArrayList;
import java.util.List;
public class Problem_5_Search_Suggestions_System {
class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isEnd = false;
}
class Trie {
TrieNode root;
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie
void insert(String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
if (node.children[ch - 'a'] == null) {
node.children[ch - 'a'] = new TrieNode();
}
node = node.children[ch - 'a'];
}
node.isEnd = true;
}
// Performs a DFS to find all words with the given prefix
void dfs(TrieNode node, List<String> list, StringBuilder word) {
if (list.size() == 3) return; // Limit to 3 suggestions
if (node.isEnd) {
list.add(word.toString());
}
for (char ch = 'a'; ch <= 'z'; ch++) {
if (node.children[ch - 'a'] != null) {
word.append(ch);
dfs(node.children[ch - 'a'], list, word);
word.deleteCharAt(word.length() - 1);
}
}
}
// Searches the trie for words starting with prefix
List<String> search(String prefix) {
TrieNode node = root;
List<String> list = new ArrayList<>();
for (char ch : prefix.toCharArray()) {
if (node.children[ch - 'a'] == null) {
return list; // No words found with this prefix
}
node = node.children[ch - 'a'];
}
dfs(node, list, new StringBuilder(prefix));
return list;
}
}
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
Trie trie = new Trie();
for (String product : products) {
trie.insert(product);
}
List<List<String>> result = new ArrayList<>();
StringBuilder prefix = new StringBuilder();
for (char ch : searchWord.toCharArray()) {
prefix.append(ch);
result.add(trie.search(prefix.toString()));
}
return result;
}
}