leetcode212
- class Solution {
- public List<String> findWords(char[][] board, String[] words) {
- List<String> res = new ArrayList<>();
- TrieNode root = buildTrie(words);
- for (int i = 0; i < board.length; i++) {
- for (int j = 0; j < board[0].length; j++) {
- dfs (board, i, j, root, res);
- }
- }
- return res;
- }
- public void dfs(char[][] board, int i, int j, TrieNode p, List<String> res) {
- char c = board[i][j];
- if (c == '#' || p.next[c - 'a'] == null) return;
- p = p.next[c - 'a'];
- if (p.word != null) { // found one
- res.add(p.word);
- p.word = null; // de-duplicate
- }
- board[i][j] = '#';
- if (i > 0) dfs(board, i - 1, j ,p, res);
- if (j > 0) dfs(board, i, j - 1, p, res);
- if (i < board.length - 1) dfs(board, i + 1, j, p, res);
- if (j < board[0].length - 1) dfs(board, i, j + 1, p, res);
- board[i][j] = c;
- }
- public TrieNode buildTrie(String[] words) {
- TrieNode root = new TrieNode();
- for (String w : words) {
- TrieNode p = root;
- for (char c : w.toCharArray()) {
- int i = c - 'a';
- if (p.next[i] == null) p.next[i] = new TrieNode();
- p = p.next[i];
- }
- p.word = w;
- }
- return root;
- }
- class TrieNode {
- TrieNode[] next = new TrieNode[26];
- String word;
- }
- }
参考:https://leetcode.com/problems/word-search-ii/discuss/59780/Java-15ms-Easiest-Solution-(100.00)
leetcode212的更多相关文章
- [Swift]LeetCode212. 单词搜索 II | Word Search II
Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...
- LeetCode212. Word Search II
https://leetcode.com/problems/word-search-ii/description/ Given a 2D board and a list of words from ...
随机推荐
- DS二叉树--左叶子数量
题目描述 计算一颗二叉树包含的叶子结点数量. 左叶子是指它的左右孩子为空,而且它是父亲的左孩子 提示:可以用三叉链表法,也可以用现有算法对两层结点进行判断 建树方法采用“先序遍历+空树用0表示”的方法 ...
- uoj #49. 【UR #3】铀仓库
http://uoj.ac/problem/49 这题二分答案可以做,同时存在另一个直接二分的解法. 考虑对每个点,二分能向左右延伸的最大半径,由于权值范围较大,不能O(1)查询向一侧走指定距离后到达 ...
- 微信小程序客服消息使用
客服消息使用 为丰富小程序的服务能力,提高服务质量,微信为小程序提供客服消息能力,以便小程序用户可以方便快捷地与小程序服务提供方进行沟通. xiaokefu.com.cn 功能介绍 用户可使用小程序客 ...
- P1002过河卒
传送 因为卒每到一个点上,就有两种情况.1.从左边过来.2.从上面过来.我们设f[i][j]为卒到[i][j]这个点的方案数,那么方程就是f[i][j]=f[i-1][j]+f[i][j-1],边界状 ...
- 服务网关zuul之七:zuul中的动态刷新路由配置
<spring扩展点之三:Spring 的监听事件 ApplicationListener 和 ApplicationEvent 用法,在spring启动后做些事情> <服务网关zu ...
- [转][Java]尝试解决Java多行字符串的编辑问题
转自:https://blog.csdn.net/jiuwuerliu/article/details/51207045 参考了:https://www.v2ex.com/amp/t/445522 除 ...
- [转]SQL数据库查询到的汉字字段是乱码
使用英文版SQL数据库查询到的汉字字段是乱码的解决方案 2007-12-04 14:55:45 标签:函数 SQL 数据库 乱码 排序规则 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出 ...
- Hbase物理模型设计
Hbase的存储结构 1.Hbase宏观架构 从上图可以看hbase集群由一个master和多个RegionServer组成,右下角是一个RegionServer的内部图. Hbase的服务器角色构成 ...
- 几种常见NPE
NPE(Null Point Exception的简称) 1.Map下的NPE 直接上代码: public class User { private Integer id; private Strin ...
- 第一次软件工程作业——html制作一份简单的个人简历
源码链接(码云):https://gitee.com/yongliuli/codes/eavjr7lxotb85s0icnq1z68 简历效果图展示: 代码展示: 添加背景音乐的方法: 在<he ...