File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 1+ var WordDictionary = function ( ) {
2+ this . dictionary = new Set ( ) ;
3+ } ;
4+
5+ /**
6+ * @param {string } word
7+ * @return {void }
8+ */
9+ WordDictionary . prototype . addWord = function ( word ) {
10+ this . dictionary . add ( word ) ;
11+ } ;
12+
13+ /**
14+ * @param {string } word
15+ * @return {boolean }
16+ */
17+
18+ // tc: O(n * k), n: dictionary size, k: word length => O(n) in worst case
19+ // sc: O(1)
20+ WordDictionary . prototype . search = function ( word ) {
21+ if ( ! word . includes ( '.' ) ) {
22+ return this . dictionary . has ( word ) ;
23+ }
24+
25+ for ( const stored of this . dictionary ) {
26+ if ( stored . length !== word . length ) continue ;
27+
28+ let isMatch = true ;
29+ for ( let i = 0 ; i < word . length ; i ++ ) {
30+ if ( word [ i ] === '.' ) continue ;
31+ if ( word [ i ] !== stored [ i ] ) {
32+ isMatch = false ;
33+ break ;
34+ }
35+ }
36+ if ( isMatch ) return true ;
37+ }
38+
39+ return false ;
40+ } ;
41+
42+ /**
43+ * Your WordDictionary object will be instantiated and called as such:
44+ * var obj = new WordDictionary()
45+ * obj.addWord(word)
46+ * var param_2 = obj.search(word)
47+ */
You can’t perform that action at this time.
0 commit comments