File tree Expand file tree Collapse file tree
design-add-and-search-words-data-structure Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import java .util .HashMap ;
2+ import java .util .Map ;
3+
4+ class WordDictionary {
5+
6+
7+ Map <Character , WordDictionary > map ;
8+ boolean isEnd = false ;
9+
10+ public WordDictionary () {
11+ map = new HashMap <>();
12+ }
13+
14+ public void addWord (String word ) {
15+ char ch = word .charAt (0 );
16+ WordDictionary node ;
17+ if (map .containsKey (ch )) {
18+ node = map .get (ch );
19+ } else {
20+ node = new WordDictionary ();
21+ }
22+
23+ map .put (ch , node );
24+
25+ if (word .length () == 1 ) {
26+ node .isEnd = true ;
27+ return ;
28+ }
29+
30+ node .addWord (word .substring (1 ));
31+ }
32+
33+ public boolean search (String word ) {
34+ if (word .length () == 0 ) {
35+ return isEnd ;
36+ }
37+
38+ char ch = word .charAt (0 );
39+ WordDictionary node ;
40+
41+ if (ch == '.' ) {
42+ for (Map .Entry <Character , WordDictionary > entry : map .entrySet ()) {
43+ if (entry .getValue ().search (word .substring (1 ))){
44+ return true ;
45+ }
46+ }
47+ }
48+
49+ if (map .containsKey (ch )) {
50+ node = map .get (ch );
51+ return node .search (word .substring (1 ));
52+ }
53+
54+ return false ;
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+ */
You can’t perform that action at this time.
0 commit comments