美文网首页
8.22 - hard - 83

8.22 - hard - 83

作者: 健时总向乱中忙 | 来源:发表于2017-08-22 23:42 被阅读0次

425. Word Squares

利用Trie和backtracking来做。利用trie来找prefix

class Solution(object):
    def wordSquares(self, words):
        """
        :type words: List[str]
        :rtype: List[List[str]]
        """
        # Write your code here
        if not words:
            return []
        root = self.buildTree(words)
        self.res = []
        self.dfs(root, [], words)
        return self.res
        
    
    def dfs(self, root, cur, words):
        if len(cur) == len(words[0]):
            self.res.append(["".join(w) for w in cur])
            return True
        
        prefix = self.getPrefix(cur)
        
        for word in self.getPrefixWords(root, prefix):
            cur.append(list(word))
            self.dfs(root, cur, words)
            cur.pop()
    
    def getPrefix(self, cur):
        pos = len(cur)
        prefix = ""
        for row in cur:
            prefix += row[pos]
        return prefix
        
    def getPrefixWords(self, root, prefix):
        # get all words with current prefix
        node = root
        for c in prefix:
            if c not in node.children:
                return []
            node = node.children[c]
        # start from current node, get all node.stop True
        return self.getWords(node, prefix, "", [])
    
    def getWords(self, node, prefix, cur, res):
        if node.stop:
            res.append(prefix+cur)
        
        for n in node.children:
            self.getWords(node.children[n], prefix, cur+n, res)
        return res

    
    def buildTree(self, words):
        root = TrieNode("")
        for word in words:
            node = root
            for c in word:
                if c not in node.children:
                    node.children[c] = TrieNode(c)
                node = node.children[c]
            node.stop = True
        
        return root


class TrieNode(object):
    def __init__(self, c):
        self.c = c
        self.stop = False
        self.children = {}

相关文章

  • 8.22 - hard - 83

    425. Word Squares 利用Trie和backtracking来做。利用trie来找prefix

  • 8.22 - hard - 85

    440. K-th Smallest in Lexicographical Order 和之前有一道386. Le...

  • 8.22 - hard - 86

    446. Arithmetic Slices II - Subsequence 一道dp的题目

  • 8.22 - hard - 87

    460. LFU Cache 有点做不动了。。。基本思想是。。。(这题要重看,先休息一会)

  • 8.22 - hard - 90

    471. Encode String with Shortest Length 一道对角线型dp题目,对角线是我自...

  • 8.22 - hard - 88

    465. Optimal Account Balancing 这道题挺有意思的,用greedy的方法

  • 8.22 - hard - 89

    466. Count The Repetitions这题好困难,看了答案也很难理解,估计只能背答案了。。。等复习的...

  • 8.22 - hard - 81

    411. Minimum Unique Word Abbreviation 利用比较基本的方法,backtrack...

  • 8.22 - hard - 84

    432. All O`one Data Structure 基本的想法就是利用一个双向链表来维持单调性,每个nod...

  • 8.22 - hard - 82

    420. Strong Password Checker 这道题要分成几种情况做When len > 20, we...

网友评论

      本文标题:8.22 - hard - 83

      本文链接:https://www.haomeiwen.com/subject/bhmrdxtx.html