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 ...
随机推荐
- java中的强,软,弱,虚引用
引用的应用场景 我们都知道垃圾回收器会回收符合回收条件的对象的内存,但并不是所有的程序员都知道回收条件取决于指向该对象的引用类型.这正是Java中弱引用和软引用的主要区别. 如果一个对象只有弱引用指向 ...
- 关于socket阻塞与非阻塞情况下的recv、send、read、write返回值---部分内容可能不确切,待讨论
1.阻塞模式与非阻塞模式下recv的返回值各代表什么意思?有没有区别?(就我目前了解阻塞与非阻塞recv返回值没有区分,都是 <0:出错,=0:连接关闭,>0接收到数据大小,特别:返回值 ...
- july 大神 要向他学习的东西(已学了)
交换礼物代码 库 permutations 库 product https://www.cnblogs.com/kaibindirver/p/10714375.html https://www.cnb ...
- Jmeter(五)录制功能
难得休息时间,和开发对完需求便理着Jmeter的知识的相关体系,趁闲暇功夫就记一点,希望这么坚持下去,能有很多关于Jmeter的知识点被总结,被挖掘出来,从而形成自己的一套知识体系..... 嗯,那本 ...
- 去掉user agent stylesheet 浏览器默认样式 [ 2.0 版本 ]
今天在写一个网页的时候发现一个问题,我的table的样式很奇怪,也没有设置什么样式,跟其他的页面不一样,打开开发者工具一看,发现有这么点样式: 其中右上角:user agent stylesheet ...
- SCCM2012 R2实战系列之四:初始化配置
在之前的文章中,我们已经完成了SCCM 2012 R2 独立主站点的部署.为了客户端代理软件的顺利安装和OSD操作系统的分发,我们需要配置组策略及DHCP服务.在本系列的第四部分,跟大家一起分享下如何 ...
- MySQL的用户密码过期功能
Payment Card Industry,即支付卡行业,PCI行业表示借记卡.信用卡.预付卡.电子钱包.ATM和POS卡及相关的业务. PCI DSS,即PCI数据安全标准(Payment Card ...
- 博客搬入CNBLOG
由于无法改变的事实,原来在163blog中的博文永久停止更新.但博文内容仍然保留,在此也谢谢网易不杀之恩.毕竟那都是博主们一个字一个字的敲出来的心血.以后新的内容会在CNBLOG中进行更新.立贴为证. ...
- (转)区分LTE,EPS,EPC和SAE
LTE:Long Term Evolution长期演进,是无线接口部分向4G演进的工作项目. 3GPP:The 3Rd Generation Partnership Project,第三代合作伙伴计划 ...
- 获取Android文件路径
Environment.getDataDirectory().getPath() : /data Environment.getDownloadCacheDirectory().getPath() : ...