File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .HashMap ;
2+ import java .util .Map ;
3+
4+ class Trie {
5+
6+ Map <Character , Trie > map ;
7+ boolean isEnd = false ;
8+
9+ public Trie () {
10+ map = new HashMap <>();
11+ }
12+
13+ public void insert (String word ) {
14+ Trie trie ;
15+ if (map .containsKey (word .charAt (0 ))) {
16+ trie = map .get (word .charAt (0 ));
17+ } else {
18+ trie = new Trie ();
19+ }
20+ map .put (word .charAt (0 ), trie );
21+
22+ if (word .length () == 1 ) {
23+ map .get (word .charAt (0 )).isEnd = true ;
24+ return ;
25+ }
26+
27+ trie .insert (word .substring (1 ));
28+ }
29+
30+ public boolean search (String word ) {
31+ if (map .containsKey (word .charAt (0 ))) {
32+ if (word .length () == 1 ) {
33+ return map .get (word .charAt (0 )).isEnd ;
34+ }
35+ return map .get (word .charAt (0 )).search (word .substring (1 ));
36+ }
37+ return false ;
38+ }
39+
40+ public boolean startsWith (String prefix ) {
41+ if (map .containsKey (prefix .charAt (0 ))) {
42+ if (prefix .length () == 1 ) {
43+ return true ;
44+ }
45+ return map .get (prefix .charAt (0 )).startsWith (prefix .substring (1 ));
46+ }
47+ return false ;
48+ }
49+ }
50+
51+ /**
52+ * Your Trie object will be instantiated and called as such:
53+ * Trie obj = new Trie();
54+ * obj.insert(word);
55+ * boolean param_2 = obj.search(word);
56+ * boolean param_3 = obj.startsWith(prefix);
57+ */
You can’t perform that action at this time.
0 commit comments