-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathLeetCode_208_18.java
More file actions
87 lines (74 loc) · 2.14 KB
/
LeetCode_208_18.java
File metadata and controls
87 lines (74 loc) · 2.14 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
package Week_04.id_18;
/**
* @author LiveForExperience
* @date 2019/6/30 11:28
*/
public class LeetCode_208_18 {
class Trie {
private static final int SIZE = 26;
private TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
if (isEmpty(word)) {
return;
}
char[] cs = word.toCharArray();
TrieNode node = root;
for (char c: cs) {
int index = c - 'a';
if (node.next[index] == null) {
node.next[index] = new TrieNode();
node.next[index].data = c;
}
node = node.next[index];
}
node.isWord = true;
}
public boolean search(String word) {
if (isEmpty(word)) {
return false;
}
char[] cs = word.toCharArray();
TrieNode node = root;
for (char c: cs) {
int index = c - 'a';
if (node.next[index] != null) {
node = node.next[index];
} else {
return false;
}
}
return node.isWord;
}
public boolean startsWith(String prefix) {
if (isEmpty(prefix)) {
return false;
}
TrieNode node = root;
char[] cs = prefix.toCharArray();
for (char c: cs) {
int index = c - 'a';
if (node.next[index] != null) {
node = node.next[index];
} else {
return false;
}
}
return true;
}
private boolean isEmpty(String word) {
return word == null || word.length() == 0;
}
private class TrieNode {
private char data;
private TrieNode[] next;
private boolean isWord;
TrieNode() {
this.next = new TrieNode[SIZE];
this.isWord = false;
}
}
}
}