-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathSolution.java
More file actions
101 lines (84 loc) · 3.17 KB
/
Copy pathSolution.java
File metadata and controls
101 lines (84 loc) · 3.17 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
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
/**
* @author Oleg Cherednik
* @since 20.01.2019
*/
public class Solution {
public static void main(String... args) {
Dictionary dictionary = new Dictionary();
dictionary.addWords(Arrays.asList("dog", "deer", "deal"));
dictionary.getWords("de").forEach(System.out::println);
}
private static final class Dictionary {
private final Node root = new Node('\0');
public void addWords(Collection<String> words) {
Optional.ofNullable(words).orElse(Collections.emptySet()).forEach(root::addWord);
}
public Set<String> getWords(String prefix) {
return getWords(prefix, findLastNode(prefix != null ? prefix.trim().toLowerCase() : null, 0, root));
}
private static Node findLastNode(String prefix, int i, Node node) {
while (true) {
if (node == null)
return null;
if (i == prefix.length())
return node;
node = node.getChild(prefix.charAt(i));
i++;
}
}
private static Set<String> getWords(String prefix, Node node) {
if (node == null)
return Collections.emptySet();
if (!node.hasChildren())
return Collections.singleton(prefix);
return collectWords(prefix, node, new TreeSet<>());
}
private static Set<String> collectWords(String prefix, Node node, Set<String> words) {
if (node == null)
return words;
if (node.end)
words.add(prefix);
if (node.hasChildren())
for (Node child : node.children)
if (child != null)
collectWords(prefix + child.ch, child, words);
return words;
}
private static final class Node {
private final char ch;
private Node[] children;
private boolean end;
public Node(char ch) {
this.ch = ch;
}
public boolean hasChildren() {
return children != null;
}
public Node getChild(char ch) {
return hasChildren() ? children[ch - 'a'] : null;
}
public void addWord(String word) {
addWord(word != null ? word.trim().toLowerCase() : null, 0, this);
}
private Node addChild(char ch) {
children = children != null ? children : new Node['z' - 'a' + 1];
children[ch - 'a'] = children[ch - 'a'] != null ? children[ch - 'a'] : new Node(ch);
return children[ch - 'a'];
}
private static void addWord(String word, int i, Node node) {
if (word == null)
return;
if (i == word.length())
node.end = true;
else
addWord(word, i + 1, node.addChild(word.charAt(i)));
}
}
}
}