FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
LeetCode-Solutions/Python/implement-magic-dictionary.py at master · Monika-R/LeetCode-Solutions · GitHub
Monika-R
/
LeetCode-Solutions
Public
forked from
kamyu104/LeetCode-Solutions
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
LeetCode-Solutions
/
Python
/
implement-magic-dictionary.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
51 lines (36 loc) · 1.41 KB
Breadcrumbs
LeetCode-Solutions
/
Python
/
implement-magic-dictionary.py
Copy path
File metadata and controls
51 lines (36 loc) · 1.41 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Time: O(n), n is the length of the word
# Space: O(d)
import
collections
class
MagicDictionary
(
object
):
def
__init__
(
self
):
"""
Initialize your data structure here.
"""
_trie
=
lambda
:
collections
.
defaultdict
(
_trie
)
self
.
trie
=
_trie
()
def
buildDict
(
self
,
dictionary
):
"""
Build a dictionary through a list of words
:type dictionary: List[str]
:rtype: void
"""
for
word
in
dictionary
:
reduce
(
dict
.
__getitem__
,
word
,
self
.
trie
).
setdefault
(
"_end"
)
def
search
(
self
,
word
):
"""
Returns if there is any word in the trie that equals to the given word after modifying exactly one character
:type word: str
:rtype: bool
"""
def
find
(
word
,
curr
,
i
,
mistakeAllowed
):
if
i
==
len
(
word
):
return
"_end"
in
curr
and
not
mistakeAllowed
if
word
[
i
]
not
in
curr
:
return
any
(
find
(
word
,
curr
[
c
],
i
+
1
,
False
)
for
c
in
curr
if
c
!=
"_end"
) \
if
mistakeAllowed
else
False
if
mistakeAllowed
:
return
find
(
word
,
curr
[
word
[
i
]],
i
+
1
,
True
)
or
\
any
(
find
(
word
,
curr
[
c
],
i
+
1
,
False
) \
for
c
in
curr
if
c
not
in
(
"_end"
,
word
[
i
]))
return
find
(
word
,
curr
[
word
[
i
]],
i
+
1
,
False
)
return
find
(
word
,
self
.
trie
,
0
,
True
)
Back
|
FazBrowse Home
|
New Git URL