File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * <a href="https://leetcode.com/problems/implement-trie-prefix-tree/">week05-3.implement-trie-prefix-tree</a>
3+ * <li>Description: Implement the Trie class </li>
4+ * <li>Topics: Hash Table, String, Design, Trie </li>
5+ * <li>Time Complexity: O(N*K), Runtime 40ms </li>
6+ * <li>Space Complexity: O(N*K), Memory 56.07MB </li>
7+ */
8+ class Trie {
9+ private boolean end ;
10+ private final Map <Character , Trie > children ;
11+
12+ public Trie () {
13+ children = new HashMap <>();
14+ }
15+
16+ public void insert (String word ) {
17+ Trie node = this ;
18+ for (Character c : word .toCharArray ()) {
19+ node = node .children .computeIfAbsent (c , k -> new Trie ());
20+ }
21+ node .end = true ;
22+ }
23+
24+ public boolean search (String word ) {
25+ Trie node = this ;
26+ for (Character c : word .toCharArray ()) {
27+ node = node .children .get (c );
28+ if (node == null ) {
29+ return false ;
30+ }
31+ }
32+ return node .end ;
33+ }
34+
35+ public boolean startsWith (String prefix ) {
36+ Trie node = this ;
37+ for (Character c : prefix .toCharArray ()) {
38+ node = node .children .get (c );
39+ if (node == null ) {
40+ return false ;
41+ }
42+ }
43+ return node != null ;
44+ }
You can’t perform that action at this time.
0 commit comments