forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
check-if-word-can-be-placed-in-crossword.py
56 lines (51 loc) · 1.96 KB
/
check-if-word-can-be-placed-in-crossword.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
49
50
51
52
53
54
55
56
# Time: O(m * n)
# Space: O(1)
class Solution(object):
def placeWordInCrossword(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
def get_val(mat, i, j, transposed):
return mat[i][j] if not transposed else mat[j][i]
def get_vecs(mat, transposed):
for i in xrange(len(mat) if not transposed else len(mat[0])):
yield (get_val(mat, i, j, transposed) for j in xrange(len(mat[0]) if not transposed else len(mat)))
for direction in (lambda x: iter(x), reversed):
for transposed in xrange(2):
for row in get_vecs(board, transposed):
it, matched = direction(word), True
for c in row:
if c == '#':
if next(it, None) is None and matched:
return True
it, matched = direction(word), True
continue
if not matched:
continue
nc = next(it, None)
matched = (nc is not None) and c in (nc, ' ')
if (next(it, None) is None) and matched:
return True
return False
# Time: O(m * n)
# Space: O(m * n)
class Solution2(object):
def placeWordInCrossword(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
words = [word, word[::-1]]
for mat in (board, zip(*board)):
for row in mat:
blocks = ''.join(row).split('#')
for s in blocks:
if len(s) != len(word):
continue
for w in words:
if all(s[i] in (w[i], ' ') for i in xrange(len(s))):
return True
return False