File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ class TrieNode {
2+ boolean word ;
3+ TrieNode [] children ;
4+
5+ TrieNode () {
6+ this .word = false ;
7+ this .children = new TrieNode [27 ];
8+ }
9+ }
10+
11+ class WordDictionary {
12+ TrieNode root ;
13+ public WordDictionary () {
14+ this .root = new TrieNode ();
15+ }
16+
17+ public void addWord (String word ) {
18+
19+ TrieNode curr = root ;
20+ for (char c : word .toCharArray ()) {
21+ if (curr .children [c - 'a' ] == null ) {
22+ curr .children [c - 'a' ] = new TrieNode ();
23+ }
24+ curr = curr .children [c - 'a' ];
25+ }
26+ curr .word = true ;
27+ }
28+
29+ public boolean search (String word ) {
30+ return dfs (word , 0 , root );
31+ }
32+
33+ public boolean dfs (String word , int index , TrieNode node ) {
34+
35+ if (index == word .length ()) {
36+ return node .word ;
37+ }
38+
39+ char c = word .charAt (index );
40+
41+ if (c == '.' ) {
42+ for (TrieNode child : node .children ) {
43+ if (child != null && dfs (word , index + 1 , child )) {
44+ return true ;
45+ }
46+ }
47+ return false ;
48+
49+ } else {
50+
51+ TrieNode next = node .children [c - 'a' ];
52+ return next != null && dfs (word , index + 1 , next );
53+
54+ }
55+ }
56+ }
You can’t perform that action at this time.
0 commit comments