Skip to content

Commit 2b18a52

Browse files
authored
Create words-within-two-edits-of-dictionary.py
1 parent 38c03d2 commit 2b18a52

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# Time: O(25 * l * (n + q))
2+
# Space: O(25 * l * n)
3+
4+
import string
5+
6+
7+
# hash
8+
class Solution(object):
9+
def twoEditWords(self, queries, dictionary):
10+
"""
11+
:type queries: List[str]
12+
:type dictionary: List[str]
13+
:rtype: List[str]
14+
"""
15+
MOD = (1<<64)-59 # largest 64-bit prime
16+
BASE = 113
17+
POW = [1]
18+
def add(a, b):
19+
return (a+b)%MOD
20+
21+
def mult(a, b):
22+
return (a*b)%MOD
23+
24+
def pow(i):
25+
while not (i < len(POW)):
26+
POW.append(mult(POW[-1], BASE))
27+
return POW[i]
28+
29+
lookup = set()
30+
for w in dictionary:
31+
h = reduce(lambda h, i: add(h, mult(ord(w[i])-ord('a'), pow(i))), xrange(len(w)), 0)
32+
for i, c in enumerate(w):
33+
for x in string.ascii_lowercase:
34+
if x == c:
35+
continue
36+
lookup.add(add(h, mult(ord(x)-ord(c), pow(i))))
37+
result = []
38+
for w in queries:
39+
h = reduce(lambda h, i: add(h, mult(ord(w[i])-ord('a'), pow(i))), xrange(len(w)), 0)
40+
for i, c in enumerate(w):
41+
for x in string.ascii_lowercase:
42+
if x == c:
43+
continue
44+
if add(h, mult(ord(x)-ord(c), pow(i))) in lookup:
45+
break
46+
else:
47+
continue
48+
result.append(w)
49+
break
50+
return result
51+
52+
53+
# Time: O(q * n * l)
54+
# Space: O(1)
55+
import itertools
56+
57+
58+
# brute force
59+
class Solution2(object):
60+
def twoEditWords(self, queries, dictionary):
61+
"""
62+
:type queries: List[str]
63+
:type dictionary: List[str]
64+
:rtype: List[str]
65+
"""
66+
return [q for q in queries if any(sum(c1 != c2 for c1, c2 in itertools.izip(q, d)) <= 2 for d in dictionary)]

0 commit comments

Comments
 (0)