-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtries.java
More file actions
73 lines (57 loc) · 1.8 KB
/
Copy pathtries.java
File metadata and controls
73 lines (57 loc) · 1.8 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
class Trie {
TrieNode root = new TrieNode('#');
/** Initialize your data structure here. */
public Trie() {
}
/** Inserts a word into the trie. */
public void insert(String word) {
root.addWord(word);
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
return root.searchChildren(word);
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
return root.startsWith(prefix);
}
}
class TrieNode {
char c = '#';
boolean hasEnd = false;
TrieNode[] children = new TrieNode[26];
// Map<Character, TrieNode> children = new HashMap<>();
public void addWord(String word) {
if (word.length() == 0) {
hasEnd = true;
return;
}
char c = word.charAt(0);
if (children[c-'a'] != null) {
children[c-'a'].addWord(word.substring(1));
} else {
TrieNode node = new TrieNode(c);
children[c-'a'] = node;
node.addWord(word.substring(1));
}
}
public TrieNode(char c) {
this.c = c;
}
public boolean startsWith(String word) {
if (word.length() == 0) return true;
char c = word.charAt(0);
if (children[c-'a'] != null) {
return children[c-'a'].startsWith(word.substring(1));
}
return false;
}
public boolean searchChildren(String word) {
if (word.length() == 0) return hasEnd;
char c = word.charAt(0);
if (children[c-'a'] != null) {
return children[c-'a'].searchChildren(word.substring(1));
}
return false;
}
}