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 must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
For example,
Given words = ["oath","pea","eat","rain"]
and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
Return ["eat","oath"]
.
解题思路:
本题承接自Java for LeetCode 079 Word Search 但是用dfs会TLE,真正的做法是将word放进Trie里面,然后遍历trie里的每个点,看是否能匹配到trie里的元素,JAVA实现如下:
public class Solution {
public List<String> findWords(char[][] board, String[] words) {
HashSet<String> list=new HashSet();
Trie trie = new Trie();
for (String word : words)
trie.insert(word);
boolean[][] visited=new boolean[board.length][board[0].length];
for (int i = 0; i < board.length; i++)
for (int j = 0; j < board[0].length; j++)
dfs(list,board, visited, "", i, j, trie);
return new ArrayList(list);
} public void dfs(Set<String> list,char[][] board, boolean[][] visited, String str, int x, int y, Trie trie) {
if (x < 0 || x >= board.length || y < 0 || y >= board[0].length)
return;
if (visited[x][y])
return;
str += board[x][y];
if (!trie.startsWith(str))
return;
if (trie.search(str))
list.add(str);
visited[x][y] = true;
dfs(list,board, visited, str, x - 1, y, trie);
dfs(list,board, visited, str, x + 1, y, trie);
dfs(list,board, visited, str, x, y - 1, trie);
dfs(list,board, visited, str, x, y + 1, trie);
visited[x][y] = false;
}
}
class TrieNode {
// Initialize your data structure here.
int num;// 有多少单词通过这个节点,即节点字符出现的次数
TrieNode[] son;// 所有的儿子节点
boolean isEnd;// 是不是最后一个节点
char val;// 节点的值 TrieNode() {
this.num = 1;
this.son = new TrieNode[26];
this.isEnd = false;
}
} class Trie {
protected TrieNode root; public Trie() {
root = new TrieNode();
} public void insert(String word) {
if (word == null || word.length() == 0)
return;
TrieNode node = this.root;
char[] letters = word.toCharArray();
for (int i = 0; i < word.length(); i++) {
int pos = letters[i] - 'a';
if (node.son[pos] == null) {
node.son[pos] = new TrieNode();
node.son[pos].val = letters[i];
} else {
node.son[pos].num++;
}
node = node.son[pos];
}
node.isEnd = true;
} // Returns if the word is in the trie.
public boolean search(String word) {
if (word == null || word.length() == 0) {
return false;
}
TrieNode node = root;
char[] letters = word.toCharArray();
for (int i = 0; i < word.length(); i++) {
int pos = letters[i] - 'a';
if (node.son[pos] != null) {
node = node.son[pos];
} else {
return false;
}
}
return node.isEnd;
} // Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
if (prefix == null || prefix.length() == 0) {
return false;
}
TrieNode node = root;
char[] letters = prefix.toCharArray();
for (int i = 0; i < prefix.length(); i++) {
int pos = letters[i] - 'a';
if (node.son[pos] != null) {
node = node.son[pos];
} else {
return false;
}
}
return true;
}
}
Java for LeetCode 212 Word Search II的更多相关文章
- [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 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
Problem: Given a 2D board and a list of words from the dictionary, find all words in the board. Each ...
- leetcode 79. Word Search 、212. Word Search II
https://www.cnblogs.com/grandyang/p/4332313.html 在一个矩阵中能不能找到string的一条路径 这个题使用的是dfs.但这个题与number of is ...
- Java for LeetCode 126 Word Ladder II 【HARD】
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- 【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 ...
- Java实现 LeetCode 212 单词搜索 II(二)
212. 单词搜索 II 给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词. 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中&quo ...
- 【LeetCode】212. Word Search II 解题报告(C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 前缀树 日期 题目地址:https://leetco ...
随机推荐
- 解决redhat的未注册问题
昨天安装第五步的时候:开始是没有网,,,居然ping不通 网 ,服务器也ping不通,,,,,可能和我前几天删除了网络适配器有关,,把linux桥接对应的适配器给删了,,, 解决办法是打开虚拟网络 ...
- 淘宝首页源码藏美女彩蛋(下)(UED新作2013egg)
我们已经知道,执行美女会得到"彩蛋",而正是彩蛋做到了taobaoUED展现给大家的神奇的前端魅力.今天我们来看看FP.egg&&FP.egg("%cjo ...
- VTK初学一,a Mesh from vtkImageData
#ifndef INITIAL_OPENGL #define INITIAL_OPENGL #include <vtkAutoInit.h> VTK_MODULE_INIT(vtkRend ...
- Spark之命令
Spark之命令 1.spark运行模式有4种: a.local 多有用测试, b. standalone:spark 集群模式,使用spark自己的调度方式. c. Yarn: 对Mapreduce ...
- 第一篇博客 iframe自适应高度
$('iframe').load(function(){ $(this).height($(this).contents().find(document).height())})这样就适应里面内 ...
- 学号160809224姓名黄家帅c语言程序设计实验2 选择结构程序设计
实验2-1 输入3个数,并按由大到小的顺序输出. 实验要求: 编写一个C程序,输入3个数,并按由大到小的顺序输出. 源码: #include <stdio.h>void main(){ i ...
- C++内存分配方式
参考:http://www.cnblogs.com/daocaoren/archive/2011/06/29/2092957.html http://www.cnblogs.com/skydesign ...
- 《lucene原理与代码分析》笔记
1.全文索引相对于顺序扫描的优势:一次索引,多次使用 2.创建索引的步骤:(1)要索引的原文档 (2)将原文档传给分词组件(Tokenizer)分词组件会做如下事情:(此过程称为Tokenize)a. ...
- Maven的作用总结
前言: maven项目也是一个项目,类似于javaProject,javaWebProject,就是多了些功能! 1 . 帮你下载jar包 maven项目会有一个 pom.xml文件, 在这个文件里面 ...
- 基于Selenium的模拟浏览器采集
Selenium 也是一个用于Web应用程序测试的工具.Selenium测试直接运行在浏览器中,就像真正的用户在操作一样.支持的浏览器包括IE(7.8.9).Mozilla Firefox.Mozil ...