首页 > 其他分享 >leetcode(31)字典树系列题目

leetcode(31)字典树系列题目

时间:2022-10-23 12:44:17浏览次数:80  
标签:node word trie 31 self 单词 board leetcode 字典

字典树,是一种是一种可以快速插入和搜索字符串的数据结构,有了它可以尽快的进行剪枝。
将字典的信息全部转化到字典树上,只有出现在字典树上的路径,才应该被纳入到搜索空间里。

搜索的时候不是比较target的pos是否匹配,而是比较当前board的字符是否出现在当前trie节点的子节点中。如果遇到了isWord节点,就需要将字符串加入最终的结果集中。

212. 单词搜索 II

class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        trie = {}
        for word in words:
            node = trie
            for ch in word:
                if ch not in node:
                    node[ch] = {}
                node = node[ch]
            node['finish'] = word
        self.res = []
        for i in range(len(board)):
            for j in range(len(board[0])):
                if board[i][j] in trie:
                    self.dfs(i, j, trie, board)
        return self.res

    def dfs(self, i, j, node, board):
        cur = board[i][j]
        isLast = node[cur].pop('finish', False)
        if isLast:
            self.res.append(isLast)
        board[i][j] = '#'
        for x, y in [[-1, 0], [1, 0], [0, 1], [0, -1]]:
            newx = i + x
            newy = j + y
            if 0 <= newx < len(board) and 0 <= newy < len(board[0]) and board[newx][newy] in node[cur]:
                self.dfs(newx, newy, node[cur], board)
        board[i][j] = cur
        if node[cur] == {}:
            node.pop(cur)

详细参考:

class Solution:
    def findWords(self, board, words):
        trie = {}

        for word in words:
            node = trie

            # 针对每个单词,构造它的字典树
            for char in word:
                if char not in node:
                    node[char] = {}
                node = node[char]
            node["finish"] = word

        # 由于我们在下面,会把添加完单词的trie剪枝,所以不用担心会添加到重复答案的问题
        self.res = []
        for i in range(len(board)):
            for j in range(len(board[0])):
                if board[i][j] in trie:
                    self.dfs(i, j, trie, board)

        return self.res

    def dfs(self, i, j, node, board):
        cur = board[i][j]
        """
        1.
        一个单词的最后一个字母的子节点只有{finish:word}了
        假如已经遍历到一个单词的最后一个字母了, pop则返回这个单词, 并记录这个单词
        假如没有遍历到一个单词的最后一个字母,pop则返回默认值False
        题目潜在假设,一个单词在一个表只能被找到一次,所以我们把这个单词找到后,pop掉单词
        例如 {a:{b:{finish:ab}}} -> {a:{b:{}}}, 然后在下面2处进行清理
        """
        isLast = node[cur].pop("finish", False)
        if isLast:
            self.res.append(isLast)

        # 本次dfs遍历过这个点,标记,在本次不会再被访问
        board[i][j] = "#"
        for x, y in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
            newi = i + x
            newj = j + y

            # 当满足所有条件的时候,我们可以把元素加进去
            if 0 <= newi <= len(board) - 1 and 0 <= newj <= len(board[0]) - 1 and board[newi][newj] in node[cur]:
                self.dfs(newi, newj, node[cur], board)
        # 本次dfs遍历完成,解除标记,在下个dfs会被再使用
        board[i][j] = cur

        """
        2. 假如存在形如这种的trie, 则把b:{}给pop掉,以减少下次查询的长度
        {a:{b:{}}} -> {a:{}}
        """
        if node[cur] == {}:
            node.pop(cur)

标签:node,word,trie,31,self,单词,board,leetcode,字典
From: https://www.cnblogs.com/ttyangY77/p/16818348.html

相关文章

  • leetcode-203-easy
    RemoveLinkedListElementsGiventheheadofalinkedlistandanintegerval,removeallthenodesofthelinkedlistthathasNode.val==val,andreturnth......
  • 数据结构 玩转数据结构 3-4 关于Leetcode的更多说明
    0课程地址https://coding.imooc.com/lesson/207.html#mid=13421 1重点关注1.1学习方法论1      自己花费了很多力气也解决不了的问......
  • 【重要】LeetCode 901. 股票价格跨度
    题目链接股票价格跨度注意事项使用单调栈代码classStockSpanner{public:StockSpanner(){this->stk.emplace(-1,INT_MAX);this->idx=-......
  • leetcode-283-easy
    MoveZeroes思路一:用left指针标记求解数组最大下标+1,初始化的时候是0,随着往右遍历,left会一步步扩大。最后把left右边的数都置为0。这题的关键在于left永远......
  • leetcode-231-easy
    PowerOfTwo思路一:观察2的n次方的二进制,都只有一位1bit,遍历即可publicbooleanisPowerOfTwo(intn){if(n<=0)returnfalse;intcount=0;......
  • LeetCode 1730. Shortest Path to Get Food
    原题链接在这里:https://leetcode.com/problems/shortest-path-to-get-food/题目:Youarestarvingandyouwanttoeatfoodasquicklyaspossible.Youwanttofind......
  • [LeetCode] 1768. Merge Strings Alternately
    Youaregiventwostrings word1 and word2.Mergethestringsbyaddinglettersinalternatingorder,startingwith word1.Ifastringislongerthantheot......
  • 【leetcode_C++_哈希表_day5】242. 有效的字母异位词&&349. 两个数组的交集&&202.快乐
    C++知识补充:(不完全,仅针对本题用的知识点)1.C++类&对象关键字public确定了类成员的访问属性。在类对象作用域内,公共成员在类的外部是可访问的。您也可以指定类的成......
  • leetcode-169-easy
    MajorityElement思路一:mappublicintmajorityElement(int[]nums){if(nums.length==1)returnnums[0];Map<Integer,Integer>map=newHashMap<>(......
  • leetcode-347. 前 K 个高频元素
    347.前K个高频元素建立一个map集合第一个元素代表当前的数字,第二个元素代表出现的次数以元素出现次数作为排序标准建立小根堆遍历map加入到堆中,当堆的长度为k的时候......