File tree Expand file tree Collapse file tree 2 files changed +73
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 2 files changed +73
-0
lines changed Original file line number Diff line number Diff line change 1+ class TrieNode :
2+ def __init__ (self ):
3+ self .links = {}
4+ self .end = False
5+
6+
7+ class WordDictionary :
8+ def __init__ (self ):
9+ self .root = TrieNode ()
10+ self .maxL = 0
11+
12+ def addWord (self , word : str ) -> None :
13+ node = self .root
14+ l = 0
15+
16+ for w in word :
17+ if w not in node .links :
18+ node .links [w ] = TrieNode ()
19+ node = node .links [w ]
20+ l += 1
21+
22+ self .maxL = max (self .maxL , l )
23+ node .end = True
24+
25+ ## TC: O(len(word)), SC: O(1)
26+
27+ def search (self , word : str ) -> bool :
28+ if len (word ) > self .maxL :
29+ return False
30+
31+ def helper (index , node ):
32+ for inn in range (index , len (word )):
33+ c = word [inn ]
34+ if c == "." :
35+ for child in node .links .values ():
36+ if helper (inn + 1 , child ):
37+ return True
38+ return False
39+ else :
40+ if c not in node .links :
41+ return False
42+ node = node .links [c ]
43+
44+ return node .end
45+
46+ return helper (0 , self .root )
47+
48+ ## TC: O(num(node)), SC: O(len(word))
Original file line number Diff line number Diff line change 1+ class Solution :
2+ def numIslands (self , grid : List [List [str ]]) -> int :
3+ res = 0
4+ rows , cols , = len (grid ), len (grid [0 ])
5+
6+ def dfs (x , y ):
7+ if x < 0 or y < 0 or x >= rows or y >= cols or grid [x ][y ] == "0" :
8+ return
9+
10+ if grid [x ][y ] == "1" :
11+ grid [x ][y ] = "0"
12+ dfs (x + 1 , y )
13+ dfs (x - 1 , y )
14+ dfs (x , y + 1 )
15+ dfs (x , y - 1 )
16+
17+ for i in range (rows ):
18+ for j in range (cols ):
19+ if grid [i ][j ] == "1" :
20+ dfs (i , j )
21+ res += 1
22+
23+ return res
24+
25+ ## TC & SC: O(m*n)
You can’t perform that action at this time.
0 commit comments