Leetcode212. Word Search II-前缀树Trie

Leetcode212. Word Search II

题目

题目链接

思路

将词典构建为Trie,
对board中的每个字母,进行dfs遍历,检查是否在Trie中

复杂度

设词典最长词的长度为L,board有M行N列

  • 时间复杂度 O ( n ) \mathcal{O}(n) O(n)
    最坏情况,board中的每个字母,向四个方向都能不停的匹配下去,直到达到字典中的单词长度,如字典为aaaaaa,board中字母也全是a,则时间复杂度为 O ( 4 ∗ L ∗ M ∗ N ) = O ( L ∗ M ∗ N ) \mathcal{O}(4*L*M*N)=\mathcal{O}(L*M*N) O(4LMN)=O(LMN)
    最好情况,board中的每个字母,在Trie中都没有匹配到起点, O ( M ∗ N ) \mathcal{O}(M*N) O(MN)

  • 空间复杂度 O ( n ) \mathcal{O}(n) O(n)
    board占用 O ( M ∗ N ) \mathcal{O}(M*N) O(MN)
    Trie:
    最坏情况,所有单词前缀都相同,如[a, ab, abc, abcd],则占用的空间为最长单词的长度, O ( L ) \mathcal{O}(L) O(L)
    最好情况,所有单词没有共用的前缀,如[a, bc, cde, defg],则占用空间为所有单词的长度之和, ∑ i = 0 l e n ( w o r d s ) O ( l e n ( w o r d s [ i ] ) ) \sum_{i=0}^{len(words)} \mathcal{O}(len(words[i])) i=0len(words)O(len(words[i])),应该在 O ( L 2 ) \mathcal{O}(L^2) O(L2)量级

代码

class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        if not board or not words:
            return []

        m = len(board)
        n = len(board[0])
        
        # 建立trie
        trie = {}
        for w in words:
            temp = trie
            for c in w:
                if c not in temp:
                    temp[c] = {}
                temp = temp[c]
            # 末尾标记
            temp['\n'] = w

        def search(trie,i,j):
            c = board[i][j]
            temp = trie[c]
            board[i][j] = ''  # 防止从o访问到a后,又回头访问o
            if '\n' in temp:  # 在trie中匹配到了完整的单词
                self.ans.append(temp.pop('\n'))
            # 向四个方向搜索
            if i > 0 and board[i-1][j] in temp:
                search(temp,i-1,j)
            if j > 0 and board[i][j-1] in temp:
                search(temp,i,j-1)
            if i < m-1 and board[i+1][j] in temp:
                search(temp,i+1,j)
            if j < n-1 and board[i][j+1] in temp:
                search(temp, i, j+1)

            board[i][j] = c

        self.ans = []
        for i in range(m):
            for j in range(n):
                # 在trie中的才进行搜索
                if board[i][j] in trie:
                    search(trie, i, j)

        return self.ans
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值