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+ // SC: O(n)
2+ // -> n is the length of the given String
3+ // TC: O(n * 26)
4+ // -> n is the length of the given String * the number of alphabets
5+ class TrieNode {
6+ TrieNode [] childNode ;
7+ boolean isEndOfWord ;
8+
9+ public TrieNode () {
10+ childNode = new TrieNode [26 ];
11+ isEndOfWord = false ;
12+ }
13+ }
14+
15+ class WordDictionary {
16+
17+ private TrieNode root ;
18+
19+ public WordDictionary () {
20+ root = new TrieNode ();
21+ }
22+
23+ public void addWord (String word ) {
24+ TrieNode node = root ;
25+
26+ for (char c : word .toCharArray ()) {
27+ int idx = c - 'a' ;
28+ if (node .childNode [idx ] == null ) {
29+ node .childNode [idx ] = new TrieNode ();
30+ }
31+ node = node .childNode [idx ];
32+ }
33+ node .isEndOfWord = true ;
34+ }
35+
36+ public boolean search (String word ) {
37+ return searchInNode (word .toCharArray (), 0 , root );
38+ }
39+
40+ private boolean searchInNode (char [] word , int idx , TrieNode node ) {
41+ if (idx == word .length ) return node .isEndOfWord ;
42+
43+ char c = word [idx ];
44+
45+ if (c == '.' ) {
46+ for (TrieNode child : node .childNode ) {
47+ if (child != null && searchInNode (word , idx +1 , child )) return true ;
48+ }
49+ return false ;
50+ } else {
51+ int childIdx = c - 'a' ;
52+ if (node .childNode [childIdx ] == null ) return false ;
53+ return searchInNode (word , idx +1 , node .childNode [childIdx ]);
54+ }
55+ }
56+ }
You can’t perform that action at this time.
0 commit comments