Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
75 lines (63 loc) · 1.83 KB

File metadata and controls

75 lines (63 loc) · 1.83 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
class TrieNode {
private final int R = 26;
private final TrieNode[] children;
private String item;
public TrieNode() {
children = new TrieNode[R];
item = "";
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public TrieNode[] getChildren() {
return children;
}
public TrieNode getChild(int i) {
if (i >= 26 || i < 0) throw new IllegalArgumentException();
return children[i];
}
public void setChild(int i, TrieNode node) {
children[i] = node;
}
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
public void insert(String word) {
TrieNode curr = root;
for (char c : word.toCharArray()) {
if (curr.getChild(c - 'a') == null) curr.setChild(c - 'a', new TrieNode());
curr = curr.getChild(c - 'a');
}
curr.setItem(word);
}
// Returns if the word is in the trie.
public boolean search(String word) {
TrieNode curr = root;
for (char c : word.toCharArray()) {
if (curr.getChild(c - 'a') == null) return false;
curr = curr.getChild(c - 'a');
}
return curr.getItem().equals(word);
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode curr = root;
for (char c : prefix.toCharArray()) {
if (curr.getChild(c - 'a') == null) return false;
curr = curr.getChild(c - 'a');
}
return true;
}
}
// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
Morty Proxy This is a proxified and sanitized view of the page, visit original site.