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 ...
随机推荐
- 弹出框三 之 sweetalert
1下载sweetalert 2.引入到项目中 <link href="~/Content/sweetalert.css" rel="stylesheet" ...
- JavaScript 学习笔记 -- Function
JS 中 函数.继承.闭包.作用域链... 一直都是硬伤,一碰到这样的问题头就大了.但是如果我继续着说:我不会,就真的无药可救了.要勇敢地说出:我的字典里就没有不会这个词,吼吼..正好昨天在书城里看了 ...
- Ubuntu之Mysql安装及基本设置
No1. Mysql 安装 sudo apt-get install mysql-server mysql-client 记得root密码别忘了. No2. 验证Mysql安装 sudo servic ...
- [设计模式] javascript 之 享元模式;
享元模式说明 定义:用于解决一个系统大量细粒度对象的共享问题: 关健词:分离跟共享: 说明: 享元模式分单纯(共享)享元模式,以及组合(不共享)享元模式,有共享跟不共享之分:单纯享元模式,只包含共享的 ...
- WCF 已知类型和泛型解析程序 KnownType
数据协定继承 已知类型和泛型解析程序 Juval Lowy 下载代码示例 自首次发布以来,Windows Communication Foundation (WCF) 开发人员便必须处理数据协定继承方 ...
- [译]git reflog
用法 git reflog 显示整个本地仓储的commit, 包括所有branch的commit, 甚至包括已经撤销的commit, 只要HEAD发生了变化, 就会在reflog里面看得到. git ...
- 使用PHP的五个小技巧
PHP的一些小技巧,比较基础,总结一下,老鸟换个姿势飘过去就是. 1. str_replace str_replace是非常常常常常用的php函数,用于字符串替换,经常看到某些php新人为了替换一批字 ...
- 隐藏NavigationBar时的一个坑
http://www.jianshu.com/p/efb960fed457 - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear: ...
- 解决访问ajax.googleapis.com链接失败方法
参考文章:http://www.jianshu.com/p/690e28f7fde6 主要思路:修改hosts文件,将其网址ajax.googleapis.com指向本地服务器:本地服务器将通过aja ...
- SQLite 数据库调研
SQLite数据库的特点(转载的): ★技术上的优点和特性 SQLite是一个轻量级.跨平台的关系型数据库.既然号称关系型数据库,支持SQL92标准中常用的玩意儿(比如视图.事务.触发器等)就是理所当 ...