S212-搜索+字典树-212. Word Search II-(Hard)
一、题目
题目很简单,输入一个字母组成的二维数组,以某一个字母为起点,向、上下左右搜索、练成的字符看是不是在给定的字符串数组中
二、解答
通过深度优先搜索,每一步和数组中的字符串匹配是可以计算出来正确结果的,但是结果超时
重点是匹配的过程时间太长
通过字典树,可以优化两点
一是检索某个字符串在不在的时间
一是一个某个字符串前缀的字符串是否存在于字符串数组中
最终的答案:
注意,结果去重
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