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:

  1. Only one letter can be changed at a time
  2. 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的更多相关文章

  1. [leetcode]Word Ladder II @ Python

    [leetcode]Word Ladder II @ Python 原题地址:http://oj.leetcode.com/problems/word-ladder-ii/ 参考文献:http://b ...

  2. LeetCode: Word Ladder II 解题报告

    Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation s ...

  3. [LeetCode] Word Ladder II 词语阶梯之二

    Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...

  4. LeetCode: Word Ladder II [127]

    [题目] Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) ...

  5. [LeetCode] Word Ladder II

    Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...

  6. leetcode—word ladder II

    1.题目描述 Given two words (start and end), and a dictionary, find all shortest transformation sequence( ...

  7. LeetCode:Word Ladder I II

    其他LeetCode题目欢迎访问:LeetCode结题报告索引 LeetCode:Word Ladder Given two words (start and end), and a dictiona ...

  8. [Leetcode Week5]Word Ladder II

    Word Ladder II 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/word-ladder-ii/description/ Descripti ...

  9. 【leetcode】Word Ladder II

      Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation ...

随机推荐

  1. hdu3507

    题意: 给n(n<=10^6)个非负数字,放在一个数组num中,再给一个特殊值m.求将这个数组分成任意多个区间,每个区间[a,b]的值定义为( sigma(num[i] | (a<=i&l ...

  2. C++学习之this指针

    C++学习之this指针 一个对象的this指针并不是对象本身的一部分,不会影响sizeof(对象)的结果.this作用域是在类内部,当在类的非静态成员函数中访问类的非静态成员的时候,编译器会自动将对 ...

  3. 决策树ID3算法[分类算法]

    ID3分类算法的编码实现 <?php /* *决策树ID3算法(分类算法的实现) */ /* *求信息增益Grain(S1,S2) */ //-------------------------- ...

  4. Dockerfile

    http://blog.csdn.net/jiashiwen/article/details/48806243 一:如何使用: Dockerfile 用来创建一个自定义的image,包含了用户指定的软 ...

  5. Windows-1252对Latin1编码有改变(并不完全兼容),而且Latin1缺失了好多西欧字符(法语,德语,西班牙语都有)

    主要是80到9F的编码被改掉了.从latin1的控制字符,变成了可以输出的可见字符. latin1编码: ISO-8859-1   x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA x ...

  6. android网络通讯数据封装之 json

    Demo程序包括客户端和服务端 客户端按json数据格式封装数据传至服务端. 服务端为简单的servlet程序,负责接收客户端传到json数据,然后按原数据返回客户端. 实例代码如下: public ...

  7. 灰度直方图及处理“cvQueryHistValue_1D”: 找不到标识符”的问题(上)

    // HIstogram.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include "opencv2/opencv.hpp ...

  8. java类的封装、继承、多态

    一.封装(encapsulation) 封装性就是把类(对象)的属性和行为结合成一个独立的相同单位,并尽可能隐蔽类(对象)的内部细节,对外形成一个边界,只保留有限的对外接口使之与外部发生联系.封装的特 ...

  9. ubuntu-12.04.4-server安装

    一.系统ISO下载      下载地址:http://www.ubuntu.com/download       根据自己的需求下载,我的电脑配置一般,因此选择32位的.   二.虚拟机配置      ...

  10. iOS判断机型

    #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> typedef NS_OPTIONS(NSInteger,D ...