1+ class WordDictionary {
2+ private static class CharDictionary {
3+ HashMap <Character , CharDictionary > charMap ;
4+ boolean isEnd ;
5+
6+ private CharDictionary () {
7+ this .charMap = new HashMap <>();
8+ this .isEnd = false ;
9+ }
10+ }
11+
12+ private CharDictionary rootNode ;
13+
14+ public WordDictionary () {
15+ this .rootNode = new CharDictionary ();
16+ }
17+
18+ public void addWord (String word ) {
19+ CharDictionary currentNode = this .rootNode ;
20+
21+ for (char ch : word .toCharArray ()) {
22+ if (!currentNode .charMap .containsKey (ch )) {
23+ currentNode .charMap .put (ch , new CharDictionary ());
24+ }
25+ currentNode = currentNode .charMap .get (ch );
26+ }
27+ currentNode .isEnd = true ;
28+ }
29+
30+ public boolean search (String word ) {
31+ return searchRecursive (word , this .rootNode , 0 );
32+ }
33+
34+ private boolean searchRecursive (String word , CharDictionary node , int index ) {
35+ // Base case
36+ if (index == word .length ()) {
37+ return node .isEnd ;
38+ }
39+
40+ char ch = word .charAt (index );
41+
42+ if (ch == '.' ) {
43+ for (CharDictionary childNode : node .charMap .values ()) {
44+ if (searchRecursive (word , childNode , index + 1 )) {
45+ return true ;
46+ }
47+ }
48+ return false ;
49+ } else {
50+ if (!node .charMap .containsKey (ch )) {
51+ return false ;
52+ }
53+ return searchRecursive (word , node .charMap .get (ch ), index + 1 );
54+ }
55+ }
56+ }
57+
58+ /**
59+ * Your WordDictionary object will be instantiated and called as such:
60+ * WordDictionary obj = new WordDictionary();
61+ * obj.addWord(word);
62+ * boolean param_2 = obj.search(word);
63+ */
0 commit comments