forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrings-differ-by-one-character.py
More file actions
31 lines (26 loc) · 928 Bytes
/
strings-differ-by-one-character.py
File metadata and controls
31 lines (26 loc) · 928 Bytes
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
# Time: O(n * m)
# Space: O(n)
import collections
class Solution(object):
def differByOne(self, dict):
"""
:type dict: List[str]
:rtype: bool
"""
MOD, P = 10**9+7, 113
hashes = [0]*len(dict)
for i, word in enumerate(dict):
for c in word:
hashes[i] = (P*hashes[i] + (ord(c)-ord('a'))) % MOD
base = 1
for p in reversed(xrange(len(dict[0]))):
lookup = collections.defaultdict(list)
for i, word in enumerate(dict):
new_hash = (hashes[i] - base*(ord(word[p])-ord('a'))) % MOD
if new_hash in lookup:
for j in lookup[new_hash]:
if dict[j][:p]+dict[j][p+1:] == word[:p]+word[p+1:]:
return True
lookup[new_hash].append(i)
base = P*base % MOD
return False