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
S212-搜索+字典树-212. Word Search II-(Hard)的更多相关文章
- leetcode 79. Word Search 、212. Word Search II
https://www.cnblogs.com/grandyang/p/4332313.html 在一个矩阵中能不能找到string的一条路径 这个题使用的是dfs.但这个题与number of is ...
- [LeetCode] 212. Word Search II 词语搜索之二
Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...
- [LeetCode] 212. Word Search II 词语搜索 II
Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...
- 【leetcode】212. Word Search II
Given an m x n board of characters and a list of strings words, return all words on the board. Each ...
- 212. Word Search II
题目: Given a 2D board and a list of words from the dictionary, find all words in the board. Each word ...
- [leetcode trie]212. Word Search II
Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...
- Java for LeetCode 212 Word Search II
Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...
- 【LeetCode】212. Word Search II 解题报告(C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 前缀树 日期 题目地址:https://leetco ...
- [LeetCode#212]Word Search II
Problem: Given a 2D board and a list of words from the dictionary, find all words in the board. Each ...
- 79. 212. Word Search *HARD* -- 字符矩阵中查找单词
79. Word Search Given a 2D board and a word, find if the word exists in the grid. The word can be co ...
随机推荐
- 实训篇-Html-注册页面【简单】
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- dbeaver导出结果集中乱码
重要的一步 需要点击
- 详解 Flink 容器化环境下的 OOM Killed
简介: 本文将解析 JVM 和 Flink 的内存模型,并总结在工作中遇到和在社区交流中了解到的造成 Flink 内存使用超出容器限制的常见原因.由于 Flink 内存使用与用户代码.部署环境.各种依 ...
- 如何利用 AHAS 保障 Web 服务稳如磐石?
简介:应用高可用服务 AHAS (Application High Availability Service) 是经阿里巴巴内部多年高可用体系沉淀下来的云产品,基于阿里开源流控降级组件 Sentin ...
- 技术干货 | 应用性能提升 70%,探究 mPaaS 全链路压测的实现原理和实施路径
简介: 全链路压测方案下,非加密场景下至少有 70% 的性能提升,加密场景下 10%的性能提升,并在 MGS 扩容完成后可实现大幅的性能提升,调优的结果远超预期. 业务背景 随着移动开发行业的步 ...
- [GPT] 对于一个复杂的html文档而言,如何用 js 批量替换页面上的某些文字从A替换为B,前提是不能去掉标签和已绑定的事件
原生:示例代码 function replaceTextInDocument(node) { if (node.nodeType === Node.TEXT_NODE) { node.textCo ...
- boom lab分析
单步调试: (gdb) bt #1 0x0000000000401347 in strings_not_equal () #2 0x0000000000400eee in phase_1 () #3 ...
- MAUI 已知问题 PathFigureCollectionConverter 非线程安全
在 MAUI 里,可以使用 PathFigureCollectionConverter 将 Path 字符串转换为 PathFigureCollection 对象,从而实现从 Path 字符串转换为路 ...
- WebGL实现简易的局部“马赛克”
前言 接触过Canvas的小伙伴应该都知道,在Canvas2D中我们要加载一个图片很简单,通过调用drawImage API就能将图像绘制到画布上,当然在WebGL中我们也可以绘制图像,在绘制时我们需 ...
- 快速搭建Zookeeper和Kafka环境
前言 由于项目需要涉及到zookeeper和Kafka的使用,快速做了一篇笔记,方便小伙伴们搭建环境. zookeeper 官方定义 What is ZooKeeper? ZooKeeper is a ...