-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution208.java
More file actions
73 lines (65 loc) · 2.22 KB
/
Copy pathSolution208.java
File metadata and controls
73 lines (65 loc) · 2.22 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 {
private boolean isEnd;
private Trie[] next; // 下一字母可能的26种映射
/** Initialize your data structure here. */
public Trie() {
isEnd = false;
next = new Trie[26];
for (int i = 0; i < 26; ++i)
next[i] = null;
}
/** Inserts a word into the trie. */
public void insert(String word) {
Trie current = this;
char[] words = word.toCharArray();
for (char cur : words){
int index = cur-'a';
if (current.next[index] == null)
current.next[index] = new Trie();
current = current.next[index];
}
current.isEnd=true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
if (isEnd == true) return false;
char[] words = word.toCharArray();
Trie current = this;
for (char cur : words){
if (current.next[cur-'a']==null)
return false;
current = current.next[cur-'a'];
}
if (current.isEnd == true) return true;
return false;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
if (isEnd == true) return false;
char[] words = prefix.toCharArray();
Trie current = this;
for (char cur : words){
if (current.next[cur-'a']==null)
return false;
current = current.next[cur-'a'];
}
return true;
}
public void print(){
Trie current = this;
for (int i = 0; i < 26; ++i) {
if (current.next[i] != null) System.out.println((char)('a'+i));
}
}
}
public class Solution208 {
public static void main(String[] args) {
Trie trie = new Trie();
trie.insert("app");
System.out.println(trie.search("apple")); // 返回 True
System.out.println(trie.search("app")); // 返回 False
System.out.println(trie.startsWith("app")); // 返回 True
trie.insert("apple");
System.out.println(trie.search("app")); // 返回 True
}
}