LeetCode :Word Ladder II My Solution
Word Ladder II
Total Accepted: 11755 Total
Submissions: 102776My Submissions
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.
这个题目着有用了不少时间,中间做了两个取巧的处理:
1.把end放到dict里面这种优点就是在BFS建立图的时候 能够直接获取end的前继,全部.这样能够降低最后处理的麻烦
2.把dfs中处理进行优化,能够直接处理到当前继没有的时候,这个时候最后一个节点一定是start
3.中间建立一个MAP map中保存不同的str相应的前继
4.假设一个串被发现了,那么要看一下是不是distance和之前的str差一个,这个是为了保证不出现绕环
5.对str的每一位做变换,使时间复杂度下来.而刚開始的时候是比較有一个位不同样,可是对海量的处理的时候反而会减少速度.
6.对最后结果要把新的放在0位,oneAnswer.add(0,end).由于是从后往前扫
public class Solution {
public ArrayList<ArrayList<String>> findLadders(String start,
String end, HashSet<String> dict) {
dict.add(end);
ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
if (start == null || end == null || start.length() != end.length()) {
return result;
}
Map<String, MyNode> map = new HashMap<String, MyNode>();
Queue<String> queue = new LinkedList<String>();
queue.offer(start);
map.put(start, new MyNode(start, 1));
while (!queue.isEmpty()) {
String cur = queue.poll();
if (reachEnd(cur, end)) {
outputResult(end, new ArrayList<String>(), map, result);
return result;
}
for (int i = 0; i < cur.length(); i++) {
for (char c = 'a'; c <= 'z'; c++) {
String changeStr = getOneDiff(cur, i, c);
if (dict.contains(changeStr)) {
MyNode curNode = map.get(cur);
int curDist = curNode.distance;
int newDist = curDist + 1;
if (!map.containsKey(changeStr)) {
MyNode newNode = new MyNode(changeStr, newDist);
newNode.pre.add(curNode);
queue.offer(changeStr);
map.put(changeStr, newNode);
} else {
MyNode preNode = map.get(changeStr);
int preDist = preNode.distance;
if (newDist == preDist) {
preNode.pre.add(curNode);
}
}
}
}
}
}
return result;
}
private void outputResult(String end, ArrayList<String> oneAnswer,
Map<String, MyNode> map, ArrayList<ArrayList<String>> result) {
MyNode curNode = map.get(end);
oneAnswer.add(0, end);
if (curNode.pre.isEmpty()) {
result.add(new ArrayList<String>(oneAnswer));
return;
}
for (MyNode eachNode : curNode.pre) {
outputResult(eachNode.val, oneAnswer, map, result);
oneAnswer.remove(0);
}
}
private void getPaths(MyNode myNode, Map<String, MyNode> map,
ArrayList<String> curPath, ArrayList<ArrayList<String>> paths) {
if (myNode == null) {
paths.add(curPath);
return;
}
curPath.add(0, myNode.val);
if (!myNode.pre.isEmpty()) {
for (MyNode prevNode : myNode.pre) {
getPaths(prevNode, map, new ArrayList<String>(curPath), paths);
}
} else {
getPaths(null, map, curPath, paths);
}
}
boolean reachEnd(String left, String right) {
if (left.equals(right)) {
return true;
}
return false;
}
String getOneDiff(String str, int pos, char c) {
StringBuffer sb = new StringBuffer(str);
sb.setCharAt(pos, c);
return sb.toString();
}
}
class MyNode {
String val;
int distance;
LinkedList<MyNode> pre;
MyNode(String v, int distance) {
this.val = v;
this.distance = distance;
pre = new LinkedList<MyNode>();
}
void addPre(MyNode p) {
pre.add(p);
}
}
不得不说,这个题做的确实痛苦,可是做AC了之后感觉非常爽!
也不知道各位大神有什么更好的办法,反正我做的时候确实感觉到非常挑战,但非常有意思.
过瘾!
LeetCode :Word Ladder II My Solution的更多相关文章
- [leetcode]Word Ladder II @ Python
[leetcode]Word Ladder II @ Python 原题地址:http://oj.leetcode.com/problems/word-ladder-ii/ 参考文献:http://b ...
- LeetCode: Word Ladder II 解题报告
Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation s ...
- [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] Word Ladder II
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- leetcode—word ladder II
1.题目描述 Given two words (start and end), and a dictionary, find all shortest transformation sequence( ...
- LeetCode:Word Ladder I II
其他LeetCode题目欢迎访问:LeetCode结题报告索引 LeetCode:Word Ladder Given two words (start and end), and a dictiona ...
- [Leetcode Week5]Word Ladder II
Word Ladder II 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/word-ladder-ii/description/ Descripti ...
- 【leetcode】Word Ladder II
Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation ...
随机推荐
- [Jobdu] 题目1506:求1+2+3+...+n
题目描述: 求1+2+3+...+n,要求不能使用乘除法.for.while.if.else.switch.case等关键字及条件判断语句(A?B:C). 输入: 输入可能包含多个测试样例. 对于每 ...
- HOJ1014
Niven Numbers My Tags (Edit) Source : Unknown Time limit : 1 sec Memory limit : 32 M Submitt ...
- Scala学习之延迟绑定
package com.swust.example object TraitDemo2 extends App{ //抽象类 abstract class Writer { def writeMess ...
- font awesome使用笔记
背景 今天将BS项目部署到IIS服务器上时.首次打开一个使用font awesome图标集的页面是加载非常慢. 于是果断按下F12查看具体页面的请求时常.除去其他异步数据的加载消耗时间以外.我居然看到 ...
- clip原理
1.clip的概述: clip是修剪之意 clip有4个属性值:inherit auto rect(20px,40px,60px,0px) !important 其中有作用的仅rect这个属性值,着重 ...
- break的使用for循环嵌套
/* Name:break的使用for循环嵌套 Copyright: By.不懂网络 Author: Yangbin Date:2014年2月21日 02:54:04 Description:以下代码 ...
- MySQL的InnoDB和MyISAM比较
InnoDB 1)虽然不支持用户创建聚族索引,但InnoDB会对主键建立聚簇索引.如果你不指定主键,InnoDB会用一个具有唯一且非空值的索引来代替.如果不存在这样的索引,InnoDB会定义一个隐藏的 ...
- C++的类型萃取技术
应该说,迭代器就是一种智能指针,因此,它也就拥有了一般指针的所有特点——能够对其进行*和->操作.但是在遍历容器的时候,不可避免的要对遍历的容器内部有所了解,所以,设计一个迭代器也就自然而然的变 ...
- rsyslog 传输日志
nginx 服务器: front-end:/usr/local/nginx/logs# cat /etc/rsyslog.conf | grep -v "^$" | grep -v ...
- 关于Struts2的碎碎念
一:安全,还是安全 我入行比较晚,那会Spring MVC什么的都很流行了,一直觉得struts2作为一个Web MVC框架实在太笨重了点.所以虽然之前一直在用,但是其实没有真正研究过. 今天公司又遇 ...