-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0425-word-squares.py
More file actions
44 lines (35 loc) · 1.32 KB
/
0425-word-squares.py
File metadata and controls
44 lines (35 loc) · 1.32 KB
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
# time complexity: O(n*26^l)
# space complexity: O(n*l)
from collections import defaultdict
from typing import List
class Solution:
def wordSquares(self, words: List[str]) -> List[List[str]]:
N = len(words[0])
prefixHashTable = defaultdict(set)
for word in words:
for prefix in (word[:i] for i in range(1, len(word))):
prefixHashTable[prefix].add(word)
def getWordsWithPrefix(prefix):
if prefix in prefixHashTable:
return prefixHashTable[prefix]
else:
return set([])
def backtracking(step, wordSquares, results):
if step == N:
results.append(wordSquares[:])
return
prefix = ''.join([word[step] for word in wordSquares])
for candidate in getWordsWithPrefix(prefix):
wordSquares.append(candidate)
backtracking(step+1, wordSquares, results)
wordSquares.pop()
results = []
wordSquares = []
for word in words:
wordSquares = [word]
backtracking(1, wordSquares, results)
return results
words = ["area", "lead", "wall", "lady", "ball"]
print(Solution().wordSquares(words))
words = ["abat", "baba", "atan", "atal"]
print(Solution().wordSquares(words))