File tree Expand file tree Collapse file tree 1 file changed +80
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +80
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ m : word length
3
+ n : Trie node count
4
+ addWord
5
+ Time Complexity: O(m)
6
+
7
+ search
8
+ Time Complexity: O(n)
9
+
10
+ Space Complexity: O(26 × N × M)
11
+
12
+ Trie + Dfs
13
+ */
14
+
15
+ class WordDictionary {
16
+ class TrieNode {
17
+ TrieNode [] children ;
18
+ boolean isEnd ;
19
+
20
+ public TrieNode () {
21
+ children = new TrieNode [26 ];
22
+ isEnd = false ;
23
+ }
24
+ }
25
+
26
+ private TrieNode root ;
27
+
28
+ public WordDictionary () {
29
+ root = new TrieNode ();
30
+ }
31
+
32
+ public void addWord (String word ) {
33
+ TrieNode current = root ;
34
+
35
+ for (char str : word .toCharArray ()) {
36
+ int idx = str - 'a' ;
37
+ if (current .children [idx ] == null ) {
38
+ current .children [idx ] = new TrieNode ();
39
+ }
40
+ current = current .children [idx ];
41
+ }
42
+ current .isEnd = true ;
43
+ }
44
+
45
+ public boolean search (String word ) {
46
+ return dfsSearch (word , 0 , root );
47
+ }
48
+
49
+ private boolean dfsSearch (String word , int idx , TrieNode node ) {
50
+ if (idx == word .length ()) {
51
+ return node .isEnd ;
52
+ }
53
+
54
+ char c = word .charAt (idx );
55
+ if (c == '.' ) {
56
+ for (int i = 0 ; i < 26 ; i ++) {
57
+ if (node .children [i ] != null ) {
58
+ if (dfsSearch (word , idx + 1 , node .children [i ])) {
59
+ return true ;
60
+ }
61
+ }
62
+ }
63
+ return false ;
64
+ } else {
65
+ int charIdx = c - 'a' ;
66
+ if (node .children [charIdx ] == null ) {
67
+ return false ;
68
+ }
69
+ return dfsSearch (word , idx + 1 , node .children [charIdx ]);
70
+ }
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Your WordDictionary object will be instantiated and called as such:
76
+ * WordDictionary obj = new WordDictionary();
77
+ * obj.addWord(word);
78
+ * boolean param_2 = obj.search(word);
79
+ */
80
+
You can’t perform that action at this time.
0 commit comments