|
| 1 | +# Time: O(m * n) |
| 2 | +# Space: O(1) |
| 3 | + |
| 4 | +class Solution(object): |
| 5 | + def placeWordInCrossword(self, board, word): |
| 6 | + """ |
| 7 | + :type board: List[List[str]] |
| 8 | + :type word: str |
| 9 | + :rtype: bool |
| 10 | + """ |
| 11 | + def get_val(mat, i, j, transposed): |
| 12 | + return mat[i][j] if not transposed else mat[j][i] |
| 13 | + |
| 14 | + def get_vecs(mat, transposed): |
| 15 | + for i in xrange(len(mat) if not transposed else len(mat[0])): |
| 16 | + yield (get_val(mat, i, j, transposed) for j in xrange(len(mat[0]) if not transposed else len(mat))) |
| 17 | + |
| 18 | + for direction in (lambda x: iter(x), reversed): |
| 19 | + for transposed in xrange(2): |
| 20 | + for row in get_vecs(board, transposed): |
| 21 | + it, matched = direction(word), True |
| 22 | + for c in row: |
| 23 | + if c == '#': |
| 24 | + if next(it, None) is None and matched: |
| 25 | + return True |
| 26 | + it, matched = direction(word), True |
| 27 | + continue |
| 28 | + if not matched: |
| 29 | + continue |
| 30 | + nc = next(it, None) |
| 31 | + matched = (nc is not None) and c in (nc, ' ') |
| 32 | + if (next(it, None) is None) and matched: |
| 33 | + return True |
| 34 | + return False |
| 35 | + |
| 36 | + |
| 37 | +# Time: O(m * n) |
| 38 | +# Space: O(m * n) |
| 39 | +class Solution2(object): |
| 40 | + def placeWordInCrossword(self, board, word): |
| 41 | + """ |
| 42 | + :type board: List[List[str]] |
| 43 | + :type word: str |
| 44 | + :rtype: bool |
| 45 | + """ |
| 46 | + words = [word, word[::-1]] |
| 47 | + for mat in (board, zip(*board)): |
| 48 | + for row in mat: |
| 49 | + blocks = ''.join(row).split('#') |
| 50 | + for s in blocks: |
| 51 | + if len(s) != len(word): |
| 52 | + continue |
| 53 | + for w in words: |
| 54 | + if all(s[i] in (w[i], ' ') for i in xrange(len(s))): |
| 55 | + return True |
| 56 | + return False |
0 commit comments