-
Notifications
You must be signed in to change notification settings - Fork 13
/
Trie.java
70 lines (62 loc) · 1.52 KB
/
Trie.java
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
package algorithm.leetcode;
/**
* @author: mayuan
* @desc:
* @date: 2018/08/12
*/
public class Trie {
Node root;
/**
* Initialize your data structure here.
*/
public Trie() {
root = new Node();
}
/**
* Inserts a word into the trie.
*/
public void insert(String word) {
Node cur = root;
for (char letter : word.toCharArray()) {
if (null == cur.children[letter - 'a']) {
cur.children[letter - 'a'] = new Node();
}
cur = cur.children[letter - 'a'];
}
cur.isEnd = true;
}
/**
* Returns if the word is in the trie.
*/
public boolean search(String word) {
Node cur = root;
for (char letter : word.toCharArray()) {
if (null == cur.children[letter - 'a']) {
return false;
}
cur = cur.children[letter - 'a'];
}
return cur.isEnd;
}
/**
* Returns if there is any word in the trie that starts with the given prefix.
*/
public boolean startsWith(String prefix) {
Node cur = root;
for (char letter : prefix.toCharArray()) {
if (null == cur.children[letter - 'a']) {
return false;
}
cur = cur.children[letter - 'a'];
}
return true;
}
class Node {
Node[] children;
boolean isEnd;
public Node() {
children = new Node[26];
isEnd = false;
}
}
}