FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode-algorithms/src/Trie.java at master · anishLearnsToCode/leetcode-algorithms · GitHub
anishLearnsToCode
/
leetcode-algorithms
Public
Notifications
You must be signed in to change notification settings
Fork
17
Star
98
Code
Issues
0
Pull requests
0
Discussions
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Discussions
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode-algorithms
/
src
/
Trie.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
59 lines (50 loc) · 1.51 KB
Breadcrumbs
leetcode-algorithms
/
src
/
Trie.java
Copy path
File metadata and controls
59 lines (50 loc) · 1.51 KB
Raw
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
// https://leetcode.com/problems/implement-trie-prefix-tree
// insertion
// T: O(n)
// S: O(n)
// search
// T: O(n)
// S: O(n)
// starts with
// T: O(n)
// S: O(n)
public
class
Trie
{
private
final
Trie
[]
alphabet
=
new
Trie
[
26
];
private
boolean
isWordEnd
=
false
;
public
Trie
() { }
public
void
insert
(
String
word
) {
insert
(
word
,
0
);
}
private
void
insert
(
String
word
,
int
index
) {
if
(
index
==
word
.
length
()) {
this
.
isWordEnd
=
true
;
return
;
}
int
charIndex
=
toIndex
(
word
.
charAt
(
index
));
if
(
alphabet
[
charIndex
] ==
null
) {
alphabet
[
charIndex
] =
new
Trie
();
}
alphabet
[
charIndex
].
insert
(
word
,
index
+
1
);
}
public
boolean
search
(
String
word
) {
return
search
(
word
,
0
);
}
public
boolean
search
(
String
word
,
int
index
) {
if
(
index
==
word
.
length
())
return
isWordEnd
;
int
charIndex
=
toIndex
(
word
.
charAt
(
index
));
if
(
alphabet
[
charIndex
] ==
null
)
return
false
;
return
alphabet
[
charIndex
].
search
(
word
,
index
+
1
);
}
public
boolean
startsWith
(
String
prefix
) {
return
startsWith
(
prefix
,
0
);
}
public
boolean
startsWith
(
String
prefix
,
int
index
) {
if
(
index
==
prefix
.
length
())
return
true
;
int
charIndex
=
toIndex
(
prefix
.
charAt
(
index
));
if
(
alphabet
[
charIndex
] ==
null
)
return
false
;
return
alphabet
[
charIndex
].
startsWith
(
prefix
,
index
+
1
);
}
private
int
toIndex
(
char
c
) {
return
c
-
'a'
;
}
}
Back
|
FazBrowse Home
|
New Git URL