-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathleetcode_208_42.java
More file actions
78 lines (67 loc) · 1.85 KB
/
leetcode_208_42.java
File metadata and controls
78 lines (67 loc) · 1.85 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
public class leetcode_208_42 {
}
public class Trie {
private final int SIZE = 26;
private TrieNode root;
class TrieNode {
private TrieNode[] son;
private boolean isWord;
private char val;
TrieNode() {
son = new TrieNode[SIZE];
isWord = false;
}
}
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
if (word.length() == 0) {
return;
}
char[] chars = word.toCharArray();
TrieNode node = root;
for (int i = 0; i < chars.length; i++) {
int pos = chars[i] - 'a';
if (node.son[pos] == null) {
node.son[pos] = new TrieNode();
node.son[pos].val = chars[i];
}
node = node.son[pos];
}
node.isWord = true;
}
public boolean search(String word) {
if (word == null || word.length() == 0) {
return false;
}
char[] chars = word.toCharArray();
TrieNode node = root;
for (int i = 0; i < chars.length; i++) {
int pos = chars[i] - 'a';
if (node.son[pos] == null) {
return false;
}
if (node.son[pos].val != chars[i]) {
return false;
}
node = node.son[pos];
}
return node.isWord;
}
public boolean startsWith(String prefix) {
if (prefix == null || prefix.length() == 0) {
return false;
}
char[] chars = prefix.toCharArray();
TrieNode node = root;
for (int i = 0; i < chars.length; i++) {
int pos = chars[i] - 'a';
if (node.son[pos].val != chars[i]) {
return false;
}
node = node.son[pos];
}
return true;
}
}