S212-搜索+字典树-212. Word Search II-(Hard)

 

一、题目

  

   题目很简单,输入一个字母组成的二维数组,以某一个字母为起点,向、上下左右搜索、练成的字符看是不是在给定的字符串数组中

 

二、解答

  通过深度优先搜索,每一步和数组中的字符串匹配是可以计算出来正确结果的,但是结果超时

  重点是匹配的过程时间太长

  通过字典树,可以优化两点

  一是检索某个字符串在不在的时间

  一是一个某个字符串前缀的字符串是否存在于字符串数组中

  最终的答案:

  注意,结果去重

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
class Trie:
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.x = {}
        self.p = {}
 
    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: void
        """
        if word:
            self.x[word] = True
            for i in range(1,len(word)+1):
                self.p[word[0:i]] = True
 
 
    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
 
        for x in self.x:
            if word == x:
                return True
        return False
 
    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie that starts with the given prefix.
        :type prefix: str
        :rtype: bool
        """
        return prefix in self.p
         
         
class Solution:
    def findWords(self, board, words):
        """
        :type board: List[List[str]]
        :type words: List[str]
        :rtype: List[str]
        """
        t = Trie()
        for word in words:
            t.insert(word)
         
        visited = [([0 for j in range(len(board[0]))]) for i in range(len(board))] 
        res = []
        for row in range(len(board)):
            for col in range(len(board[0])):
                self.DFS(board, visited, "", row, col, t, res)
                 
        return list(set(res))
                 
    def DFS(self, board, visited, temp_str, pos_row, pos_col, t, res):
        if pos_row < 0 or pos_row >= len(board) or pos_col < 0 or pos_col >= len(board[0]):
            return
#       print(pos_row, pos_col, visited)
        if visited[pos_row][pos_col] == 1:
            return
        temp_str += board[pos_row][pos_col]
        if not t.startsWith(temp_str):
            return
        if t.search(temp_str):
            res.append(temp_str)
             
        visited[pos_row][pos_col] = 1
        self.DFS(board, visited, temp_str, pos_row, pos_col + 1, t, res)
        self.DFS(board, visited, temp_str, pos_row - 1, pos_col, t, res)
        self.DFS(board, visited, temp_str, pos_row, pos_col - 1, t, res)
        self.DFS(board, visited, temp_str, pos_row + 1, pos_col, t, res)
        visited[pos_row][pos_col] = 0
             
         
         
         
         
if __name__ == "__main__":
    s = Solution()
#   print(s.findWords([
#           ['o','a','a','n'],
#           ['e','t','a','e'],
#           ['i','h','k','r'],
#           ['i','f','l','v']
#       ],
#       ["oath","pea","eat","rain"]))
     
    print(s.findWords([["b"],["a"],["b"],["b"],["a"]],
                        ["baa","abba","baab","aba"]))  

  

三、参考

  https://blog.csdn.net/ljiabin/article/details/45846527

posted @   兜兜有糖的博客  阅读(275)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示