-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmagic_dictionary.py
48 lines (37 loc) · 1.39 KB
/
magic_dictionary.py
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
48
#
# https://leetcode.com/problems/implement-magic-dictionary/
#
from string import ascii_lowercase
class MagicDictionary(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.hashes = {}
def buildDict(self, dictonary):
"""
Build a dictionary through a list of words
:type dict: List[str]
:rtype: None
"""
self.hashes = set(dictonary)
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
"""
for idx, letter in enumerate(word):
for l in ascii_lowercase:
if l != letter:
if word[:idx] + l + word[idx + 1:] in self.hashes:
return True
return False
dictionary = ["a","b","ab","abc","abcabacbababdbadbfaejfoiawfjaojfaojefaowjfoawjfoawj","abcdefghijawefe","aefawoifjowajfowafjeoawjfaow","cba","cas","aaewfawi","babcda","bcd","awefj"]
f = MagicDictionary()
f.buildDict(dictionary)
inp = ["a", "b", "c", "d", "e", "f", "ab", "ba", "abc", "cba", "abb", "bb", "aa", "bbc", "abcd"]
res = [True, True, True, True, True, True, False, False, False, False, True, True, True, True, False]
f.search("abc")
for idx, w in enumerate(inp):
assert f.search(w) is res[idx]