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. IIS发布网站后局域网其他用户不能访问问题(转)

    如果本机能正常访问,而局域网其他用户不能访问,那么判断的结果很可能是防火墙问题. 解决方法: 既然问题出在Windows7或Windows Server 2008 R2的防火墙上,那么我们可以有以下两 ...

  2. OSCache缓存框架介绍

          OSCache是一种开放性的JSP定制标记应用,由OpenSymphony设计,提供了在现有JSP页面之内实现快速内存缓冲的功能. OSCache是个一个广泛采用的高性能的J2EE缓存框架 ...

  3. $()和getElementById()的区别

    jQuery的成功多归功于其强大的选择器. 然而,相信不少初学jQuery的同学都会遇到下面的问题. 在javascript下,我们可以根据getElementById()来获取页面元素.如下: va ...

  4. MarkDown使用 (一)

    MarkDown的数学公式输入 MarkDown的数学公式输入 1.如何插入公式 LaTeX的数学公式有两种:行中公式和独立公式.行中公式放在文中与其它文字混编,独立公式单独成行. 行中公式可以用如下 ...

  5. java下拉框,滚动条

    package com.soft.test; /** * 下拉列表.下拉框.滚动条的使用 */ import javax.swing.*; import java.awt.*; public clas ...

  6. Asp.Net 禁用cookie后使用session

    原文地址:http://www.c-sharpcorner.com/UploadFile/deepak.sharma00/using-cookie-less-session-in-Asp-Net/ H ...

  7. JavaEE Tutorials (12) - 创建和使用基于字符串的Criteria查询

    12.1基于字符串的Criteria API查询概述17812.2创建基于字符串的查询17812.3执行基于字符串的查询179

  8. Azure 网站和通配符域

     本文章由Azure 网站团队软件开发工程师Michael Candido 撰写 一些 Web 应用程序需要使用多个子域,在某些情况下还需要动态添加新的子域.例如,一个多租户 Web 应用程序可使 ...

  9. java的抽象类

    现实世界中,人们表征世界时,会把现实世界中的很多类具有相同特征的事物归为一个抽象类.比如水果是许多植物果实的总称,我们可以定义一个苹果类.定义一个西瓜类,可以实例化一个苹果对象,可以实例化一个西瓜对象 ...

  10. wamp+thinkphp环境配置

    下载wamp并安装,启动wamp,会出现一个小图标,然后点击它——>Start All Services.我点击之后是橙色,不是绿色.绿色代表成功启动.我是IIS占用了80端口的缘故,所以我修改 ...