Given two words (start and end), and a dictionary, find the length of shortest transformation sequence 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"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Note:

    • Return 0 if there is no such transformation sequence.
    • All words have the same length.
    • All words contain only lowercase alphabetic characters.

乍看起来很难的一题,其实仔细分析就是图的遍历。把start,end和dict里的词都看作一个个结点,如果一个词可以合法转化为另一个词,那么视为这两个“结点”中间有一条路径。问题则变为,找到从start到end的最短路径长度。

如果采用扫描所有dict中单词,然后判断是否合法来遍历结点的方法,会超时(因为有dict中单词过多的用例)。所以只能采用别的遍历思路。

一个有效的遍历思路是获取到当前单词长度,然后对每一位都尝试替换为别的字符来遍历,即得到所以可能的合法字符串,然后判断是否等于end,或者在dict中且不在已遍历过的结点中,这样时间复杂度就是O(l)仅仅跟单词长度有关了。

对每一个结点,都用HashMap保存start到它的路径长度,新结点进入时只需要把长度加一即可。

采用广度优先遍历比较好,因为我们只需要获得最短的路径长度,而广度优先可以保证第一个到达end的路径是最短的(即到达end即可以return)。

代码如下:

     public int ladderLength(String start, String end, Set<String> dict) {
HashMap<String, Integer> hm = new HashMap<String, Integer>();
Queue<String> q = new LinkedList<String>();
q.add(start);
hm.put(start,1); while(!q.isEmpty())
{
String temp = q.poll();
int len = hm.get(temp);
for(int i=0;i<temp.length();i++) {
for(char c='a';c<='z';c++) {
if(c==temp.charAt(i))
continue;
StringBuilder sb = new StringBuilder(temp);
sb.setCharAt(i,c);
String next = sb.toString(); if(next.equals(end))
return len+1;
if(dict.contains(next) && !hm.containsKey(next)) {
q.add(next);
hm.put(next,len+1);
}
}
}
}
return 0;
}

[Leetcode][JAVA] Word Ladder的更多相关文章

  1. [Leetcode][JAVA] Word Ladder II

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

  2. Java for LeetCode 126 Word Ladder II 【HARD】

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

  3. LeetCode 126. Word Ladder II 单词接龙 II(C++/Java)

    题目: Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transfo ...

  4. [LeetCode] 126. Word Ladder II 词语阶梯 II

    Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...

  5. [LeetCode] 127. Word Ladder 单词阶梯

    Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...

  6. LeetCode 127. Word Ladder 单词接龙(C++/Java)

    题目: Given two words (beginWord and endWord), and a dictionary's word list, find the length of shorte ...

  7. [LeetCode#128]Word Ladder II

    Problem: Given two words (start and end), and a dictionary, find all shortest transformation sequenc ...

  8. [Leetcode Week5]Word Ladder II

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

  9. [Leetcode Week5]Word Ladder

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

随机推荐

  1. React 附件动画API ReactCSSTransitionGroup

    React为动画提供了一个附加组件ReactTransitionGroup,这个附加组件是动画的底层API,并且还提供了一个附件组件ReactCSSTransitionGroup,ReactCSSTr ...

  2. jquery 选择器汇总

    jQueryAPI_1.7.1_CN.chm下载地址http://download.csdn.net/detail/zhai123_/6459563 jquery 选择器大体上可分为4 类: 1.基本 ...

  3. 通过案例对 spark streaming 透彻理解三板斧之一: spark streaming 另类实验

    本期内容 : spark streaming另类在线实验 瞬间理解spark streaming本质 一.  我们最开始将从Spark Streaming入手 为何从Spark Streaming切入 ...

  4. iOS软件开发架构理解

    这个东西是硬伤,框架?自带的mvc? 自带的UIViewController UIView UINavigationController 这些算不算?当然算的,cocoa框架嘛,大家都知道. 其实,我 ...

  5. win7,xp通用的打开文件浏览对话框的方法

    第一种:Function BrowseForFile()     Dim shell : Set shell = CreateObject("WScript.Shell")     ...

  6. 百度地图API示例之移动地图

    级别为6 级别为8 级别为12 代码: <!DOCTYPE html> <html> <head> <meta http-equiv="Conten ...

  7. 判断 0 和 '' 以及 empty null false的关系

    if('safdasefasefasf'==0) { echo "该字符串转换为数字 等于 0 <br/>"; } //output:该字符串转换为数字 等于零. 这是 ...

  8. Python自动化 【第六篇】:Python基础-面向对象

      目录: 面向过程VS面向对象 面向对象编程介绍 为什么要用面向对象进行开发 面向对象的特性:封装.继承.多态 面向过程 VS 面向对象 面向过程编程(Procedural Programming) ...

  9. git免密码pull,push

    执行git config --global credential.helper store

  10. 使用VisualVM监控远程服务器JVM

    VisualVM是JDK自带的一款全能型性能监控和故障分析工具,包括对CPU使用.JVM堆内存消耗.线程.类加载的实时监控,内存dump文件分析,垃圾回收运行情况的可视化分析等,对故障排查和性能调优很 ...