File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Trie {
2
+ Set <String > dict ;
3
+
4
+ public Trie () {
5
+ dict = new TreeSet <>();
6
+ }
7
+
8
+ public void insert (String word ) {
9
+ dict .add (word );
10
+ }
11
+
12
+ public boolean search (String word ) {
13
+ if (dict .contains (word )) return true ;
14
+ return false ;
15
+ }
16
+
17
+ public boolean startsWith (String prefix ) {
18
+ for (String saved : dict ){
19
+ int count = 0 ;
20
+ if (prefix .compareTo (saved ) > 0 ) continue ;
21
+ if (prefix .length () > saved .length ()) continue ;
22
+
23
+ for (int i = 0 ; i < prefix .length (); i ++){
24
+ if (prefix .charAt (i ) != saved .charAt (i )) break ;
25
+ count ++;
26
+ }
27
+ if (count == prefix .length ()) return true ;
28
+ }
29
+ return false ;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Your Trie object will be instantiated and called as such:
35
+ * Trie obj = new Trie();
36
+ * obj.insert(word);
37
+ * boolean param_2 = obj.search(word);
38
+ * boolean param_3 = obj.startsWith(prefix);
39
+ */
40
+
You can’t perform that action at this time.
0 commit comments