LeetCode: Word Ladder II 解题报告
Word Ladder II
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
Return
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
Note:
All words have the same length.
All words contain only lowercase alphabetic characters.
![]()
SOLUTION 1:
这题做得真累,主页君差点一口老血吐在屏幕上,感觉一不小心就会超时了。
其实最后还是可以采用跟Word Ladder 1一样的解法。使用BFS遍历可能的解。不同的有以下几点:
1. 分层次遍历的时候,不要把找到的解的单词直接放在MAP中,而是可以放在别的一个临时的MAP中,一层遍历完成后,再统一加到MAP。这样做的上的是:
如果本层找到一个单词比如Word,本层的其它单词如果也可以到达Word,我们仍然要把它的解都记下来。
2. 添加到队列的时候,也要判断是不是一个新的单词(在临时MAP中查一下),是新的才能放在Queue中,否则因为1的关系,我们会计算某个单词的所有的解,所以会一直访问它。为了避免重复加入一个单词,这一步是有必要的。
3. 与Word Ladder1中的set不同,我们使用一个hasmap来记录路径中的单词,另外,每一个单词对应的value是一个string的list,记录到达此单词的所有的可能的路径。创建这些路径的方法是:把前节点的所有的路径加上当前单词,复制一份加过来即可。
REF: http://blog.csdn.net/whuwangyi/article/details/21611433
public class Solution {
public static List<List<String>> findLadders(String start, String end, Set<String> dict) {
if (start == null || end == null) {
return null;
}
Queue<String> q = new LinkedList<String>();
// 存储每一个单词对应的路径
HashMap<String, List<List<String>>> map = new HashMap<String, List<List<String>>>();
// 标记在某一层找到解
boolean find = false;
// store the length of the start string.
int lenStr = start.length();
List<List<String>> list = new ArrayList<List<String>>();
// 唯一的路径
List<String> path = new ArrayList<String>();
path.add(start);
list.add(path);
// 将头节点放入
map.put(start, list);
q.offer(start);
while (!q.isEmpty()) {
int size = q.size();
HashMap<String, List<List<String>>> mapTmp = new HashMap<String, List<List<String>>>();
for (int i = 0; i < size; i++) {
// get the current word.
String str = q.poll();
for (int j = 0; j < lenStr; j++) {
StringBuilder sb = new StringBuilder(str);
for (char c = 'a'; c <= 'z'; c++) {
sb.setCharAt(j, c);
String tmp = sb.toString();
// 1. 重复的单词,不需要计算。因为之前一层出现过,再出现只会更长
// 2. 必须要在字典中出现
if (map.containsKey(tmp) || (!dict.contains(tmp) && !tmp.equals(end))) {
continue;
}
// 将前节点的路径提取出来
List<List<String>> pre = map.get(str);
// 从mapTmp中取出节点,或者是新建一个节点
List<List<String>> curList = mapTmp.get(tmp);
if (curList == null) {
// Create a new list and add to the end word.
curList = new ArrayList<List<String>>();
mapTmp.put(tmp, curList);
// 将生成的单词放入队列,以便下一次继续变换
// 放在这里可以避免Q重复加入
q.offer(tmp);
}
// 将PRE的path 取出,加上当前节点,并放入curList中
for(List<String> pathPre: pre) {
List<String> pathNew = new ArrayList<String>(pathPre);
pathNew.add(tmp);
curList.add(pathNew);
}
if (tmp.equals(end)) {
find = true;
}
}
}
}
if (find) {
return mapTmp.get(end);
}
// 把当前层找到的解放在MAP中。
// 使用2个map的原因是:在当前层中,我们需要把同一个单词的所有的解全部找出来.
map.putAll(mapTmp);
}
// 返回一个空的结果
return new ArrayList<List<String>>();
}
}
2014.12.18 Redo:
做了一个小小的优化,拿掉了Find Flag:
public class Solution {
public static List<List<String>> findLadders(String start, String end, Set<String> dict) {
List<List<String>> ret = new ArrayList<List<String>>();
if (start == null || end == null || dict == null) {
return ret;
}
HashMap<String, List<List<String>>> map = new HashMap<String, List<List<String>>>();
// Store the map of the current level.
HashMap<String, List<List<String>>> mapTmp = new HashMap<String, List<List<String>>>();
Queue<String> q = new LinkedList<String>();
q.offer(start);
List<List<String>> listStart = new ArrayList<List<String>>();
// 唯一的路径
List<String> path = new ArrayList<String>();
path.add(start);
listStart.add(path);
// 将头节点放入
map.put(start, listStart);
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
String s = q.poll();
int len = s.length();
for (int j = 0; j < len; j++) {
StringBuilder sb = new StringBuilder(s);
for (char c = 'a'; c <= 'z'; c++) {
// Bug 2: should seperate the setCharAt(j, c) function and the sb.toString() function.
sb.setCharAt(j, c);
String tmp = sb.toString();
// 1. 不在字典中,并且不是end.
// 2. 前面的map中已经出现过
// Bug 1: map should use containsKey;
if ((!dict.contains(tmp) && !tmp.equals(end)) || map.containsKey(tmp)) {
continue;
}
// Try to get the pre list.
List<List<String>> pre = map.get(s);
// 从mapTmp中取出节点,或者是新建一个节点
List<List<String>> curList = mapTmp.get(tmp);
if (curList == null) {
curList = new ArrayList<List<String>>();
// Only offer new string to the queue.
// 将生成的单词放入队列,以便下一次继续变换
// 放在这里可以避免Q重复加入
q.offer(tmp);
// create a new map.
mapTmp.put(tmp, curList);
}
// 将PRE的path 取出,加上当前节点,并放入curList中
for (List<String> strList: pre) {
// Should create a new list.
List<String> strListNew = new ArrayList<String>(strList);
strListNew.add(tmp);
curList.add(strListNew);
}
}
}
}
if (mapTmp.containsKey(end)) {
return mapTmp.get(end);
}
// add the tmp map into the map.
map.putAll(mapTmp);
}
return ret;
}
}
SOLUTION 2:
http://www.ninechapter.com/solutions/
GITHUB:
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/string/FindLadders.java
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/string/FindLadders_1218_2014.java
LeetCode: Word Ladder II 解题报告的更多相关文章
- LeetCode: Word Break II 解题报告
Word Break II Given a string s and a dictionary of words dict, add spaces in s to construct a senten ...
- 【原创】leetCodeOj --- Word Ladder II 解题报告 (迄今为止最痛苦的一道题)
原题地址: https://oj.leetcode.com/submissions/detail/19446353/ 题目内容: Given two words (start and end), an ...
- [leetcode]Word Ladder II @ Python
[leetcode]Word Ladder II @ Python 原题地址:http://oj.leetcode.com/problems/word-ladder-ii/ 参考文献:http://b ...
- LeetCode :Word Ladder II My Solution
Word Ladder II Total Accepted: 11755 Total Submissions: 102776My Submissions Given two words (start ...
- 【LeetCode】Permutations II 解题报告
[题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...
- LeetCode: Unique Paths II 解题报告
Unique Paths II Total Accepted: 31019 Total Submissions: 110866My Submissions Question Solution Fol ...
- [LeetCode] Word Ladder II 词语阶梯之二
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- LeetCode: Word Ladder II [127]
[题目] Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) ...
- 【LeetCode】212. Word Search II 解题报告(C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 前缀树 日期 题目地址:https://leetco ...
随机推荐
- 〖Windows〗zigbee实验之cygwin编译TestSimpleMac并测试通信
1. 开发环境及工具: 1) cygwin安装包下载地址:cygwin-files.zip >>安装时选择本地目录(Select local Package directory),其 ...
- @Autowired(required = false)
标记在 方法上的时候,它会根据类型去spring容器中寻找 对于的形参并且注入. @Repository(value="userDao") public class UserDao ...
- 锋利的jQuery(第二版)源码下载地址
书上给的http://cssrain.sinaapp.com无法访问 问作者邮箱要的: 第1版源码:百度云盘下载:http://pan.baidu.com/share/link?shareid=104 ...
- Servlet乱码问题
数据像水流一样从一个地方流向另一个地方. 文本流是特殊的二进制流. 既然提到乱码问题,那就必然是用错误的编码去解释二进制流. 在传输过程中必然都是以二进制流传输的. 所以,我们需要考虑的是: 有几个数 ...
- 【LeetCode】144. Binary Tree Preorder Traversal (3 solutions)
Binary Tree Preorder Traversal Given a binary tree, return the preorder traversal of its nodes' valu ...
- 马哥 Linux文本处理和文件查找 笔记
grep: Global RE(Regular Expression) Printing文本过滤工具,能够实现根据指定的"模式(Pattern)"逐行搜索文件内容,并将匹配到的行显 ...
- WSDL格式
http://www.blogjava.net/charles/archive/2008/12/15/246368.html最近写Web service, 很多代码是用工具生成的,可以说只知其然,不知 ...
- iOS - CFNetwork 的使用
1.CFNetwork CFNetwork 是基于 OS 层 BSDSocket 封装(纯 C),用于网络通信,早期的网络请求框架 ASIHTTPRequest 就是基于 CFNetwork 进行的封 ...
- go 学习笔记(1)--package
引入包有以下几种方式: 1. 最简单的方式引入一个包的方式是直接引入包,例如: import "fmt" import "os" 2. 也可以通过下面的方式将包 ...
- 在linux下导入.sql文件,数据库中文乱码
现象描述 我是在aix下面导入如下SQL语句时,数据库中显示乱码. insert into CONFERENCE(CONFERENCEID,SUBCONFERENCEID,ACCESSNUMBER,A ...