leetcode Add to List 425. Word Squares

来源:互联网 发布:java用户登录权限 编辑:程序博客网 时间:2024/06/08 06:42

leetcode   Add to List 425. Word Squares

zip(*)  当前列就是下一行的前缀,用这个来遍历, square 为4时输出方阵。

class Solution(object):    def wordSquares(self, words):        """        :type words: List[str]        :rtype: List[List[str]]        """        n = len(words[0])        full = collections.defaultdict(list)        for word in words:            for i in range(n):                full[word[:i+1]].append(word)        squares = []        def build(square):            if len(square)==n:                squares.append(square)                return             pre = "".join(zip(*square)[len(square)])            if pre in full:                for word in full["".join(zip(*square)[len(square)])]:                    build(square + [word])        for word in words:            build([word])                return squares