-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutocompleteSystem.java
More file actions
53 lines (46 loc) · 1.59 KB
/
Copy pathAutocompleteSystem.java
File metadata and controls
53 lines (46 loc) · 1.59 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
import java.util.*;
class TrieNode {
Map<Character, TrieNode> children = new HashMap<>();
boolean isWord = false;
int frequency = 0;
}
public class AutocompleteSystem {
TrieNode root = new TrieNode();
public void insert(String word) {
TrieNode curr = root;
for (char ch : word.toCharArray()) {
curr = curr.children.computeIfAbsent(ch, c -> new TrieNode());
}
curr.isWord = true;
curr.frequency++;
}
public List<String> suggest(String prefix) {
TrieNode node = root;
for (char ch : prefix.toCharArray()) {
if (!node.children.containsKey(ch)) return new ArrayList<>();
node = node.children.get(ch);
}
List<String> results = new ArrayList<>();
dfs(node, prefix, results);
return results;
}
private void dfs(TrieNode node, String word, List<String> list) {
if (node.isWord) list.add(word);
for (char ch : node.children.keySet()) {
dfs(node.children.get(ch), word + ch, list);
}
}
public static void main(String[] args) {
AutocompleteSystem ac = new AutocompleteSystem();
ac.insert("cat");
ac.insert("car");
ac.insert("cart");
ac.insert("camera");
Scanner sc = new Scanner(System.in);
System.out.print("Enter prefix: ");
String pre = sc.nextLine();
List<String> out = ac.suggest(pre);
System.out.println("Suggestions:");
for (String word : out) System.out.println(word);
}
}