import java.util.*;

/**
* Source : https://oj.leetcode.com/problems/word-ladder/
*
*
* Given two words (start and end), and a dictionary, find the length of shortest
* transformation sequence 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"]
*
* 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.
*
*/
public class WordLadder { /**
*
* 转化为图的问题
* start、end、dict中各个单词看做是图中的每个节点
* 如果有一个单词能变化一个字母到另外一个单词,说明两个节点是连通的
*
* 所以就转化为求两个节点之间的最短距离,使用BFS
*
* 使用BFS注意:
* 1. 找到当前需要遍历的节点,这里是当前节点的相邻节点
* 2. 标记已经遍历过的节点,防止从重复遍历
*
* 从start开始使用BFS,遍历当前节点的相邻节点,求出当前节点的相邻节点两种办法:
* 1. 遍历字典中每个单词,如果和当前单词只差一个字母,说明是相邻的,复杂度为:w*n,w是当前单词的长度,n是字典单词数量
* 2. 针对当前单词的每个字母,找出可能得变化,每个字母可以变为26个字母中除本身外的其他字母,如果判断变化后的单词在字典中则为相邻的节点,
* 复杂度为 26*w,w为单词长度
*
* 当字典中单词数量较小的时候可以使用第一种方法,如果字典中单词数量较大则使用第二种方法
*
* 怎么标记访问过的节点?
* 已经访问过的节点不需要再次被访问,所以可以从字典中删除
*
* 这里使用第二种方法
*
* @param start
* @param end
* @param dict
* @return
*/
public int ladderLength (String start, String end, String[] dict) {
Set<String> set = new HashSet<String>(Arrays.asList(dict));
set.add(end);
Map<String, Integer> map = new HashMap<String, Integer>(); map.put(start, 1);
while (map.size() > 0) {
String cur = map.keySet().iterator().next();
Integer len = map.get(cur);
if (cur.equals(end)) {
System.out.println(len);
// return len;
}
map.remove(cur);
Set<String> neighbors = findNeighbors(cur, set);
for (String str : neighbors) {
map.put(str, len+1);
}
} return 0; } private Set<String> findNeighbors (String cur, Set<String> dict) {
Set<String> neighbors = new HashSet<String>();
for (int i = 0; i < cur.length(); i++) {
for (int j = 0; j < 26; j++) {
char ch = (char) ('a' + j);
if (cur.charAt(i) != ch) {
String candidate = "";
if (i == cur.length()-1) {
candidate = cur.substring(0, i) + ch;
} else {
candidate = cur.substring(0, i) + ch + cur.substring(i+1);
}
if (dict.contains(candidate)) {
neighbors.add(candidate);
dict.remove(candidate);
}
}
}
}
return neighbors;
} public static void main(String[] args) {
WordLadder wordLadder = new WordLadder();
String start = "hit";
String end = "cog";
String[] dict = new String[]{"hot","dot","dog","lot","log"};
System.out.println(wordLadder.ladderLength(start, end, dict) + "----5"); }
}

leetcode — word-ladder的更多相关文章

  1. LeetCode:Word Ladder I II

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

  2. [leetcode]Word Ladder II @ Python

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

  3. [LeetCode] Word Ladder 词语阶梯

    Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformatio ...

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

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

  5. LeetCode :Word Ladder II My Solution

    Word Ladder II Total Accepted: 11755 Total Submissions: 102776My Submissions Given two words (start  ...

  6. LeetCode: Word Ladder II 解题报告

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

  7. LeetCode: Word Ladder II [127]

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

  8. LeetCode Word Ladder 找单词变换梯

    题意:给出两个单词,以及一个set集合,当中是很多的单词.unordered_set是无序的集合,也就是说找的序列也是无序的了,是C++11的标准,可能得升级你的编译器版本了.要求找出一个从start ...

  9. [leetcode]Word Ladder @ Python

    原题地址:https://oj.leetcode.com/problems/word-ladder/ 题意: Given two words (start and end), and a dictio ...

  10. Leetcode Word Ladder

    Given two words (start and end), and a dictionary, find the length of shortest transformation sequen ...

随机推荐

  1. VMware Workstation安装Red hat7.0联网问题总结

    1.在red hat7当中iconfig命令是被取消了的,开发者用ip addr命令取代了ifconfig命令. 当然也是可以用ifconfig命令的 (前提是你安装的linux是可以联网的): 1) ...

  2. 【工作手札】Nginx接口代理可跨域

    接口代理nginx配置 location /api/ { proxy_set_header Host api.shenjian.io; proxy_set_header X-Forwarded-For ...

  3. 1、搭建 maven 环境

    1.创建 Maven 工程 这里需要注意的: 创建时,需要将 maven 工程的打包方式设置为 war,因为我们创建的是一个web工程 创建后,可能会报错,会提示没有 web.xml 文件,这是因为 ...

  4. python学习:元组和嵌套

    tuple(元组):只是可读,不可以修改# tup1 = () #空元组# tup2 = (20,) #元组内有一个元素,需要在元素后添加逗号 a = (1,2,3,4)print(a[1])a[1] ...

  5. 873D. Merge Sort

    Merge sort is a well-known sorting algorithm. The main function that sorts the elements of array a w ...

  6. gym 101628

    前几天感冒了三天没怎么写题...今天好很多了打个三星场找点手感. 不行啊我好菜啊.只会8个..补题的话,再说吧.G题感觉值得一补. 补了G,K不想写B不会. 说实话这个三星场还是很新人向的,知识点也蛮 ...

  7. [转载]SSH框架搭建详细图文教程

    http://www.cnblogs.com/hoobey/p/5512924.html

  8. PIL成就你的自信之路

    1.强大的PIL库 在Python中,有一个优秀的图像处理框架,就是PIL库,本博文会分模块,介绍PIL库中的各种方法,并列举相关例子. 学习总结:PIL库可以让我们得到更多的需求,以此来满足我们的需 ...

  9. ubuntu Pycharm 2017 3.3 Active

    1.打开激活窗口 2.选择 Activate new license with License server (用license server 激活) 3.在 License sever addres ...

  10. 谈一谈从 Delphi 2009 之后就支援的重要功能 – 泛型 (Generic)

    前言 在C++的语言基础当中,除了物件导向.事件驱动的概念之外,模版设计(Template)也是非常重要的一环.然而,C++的开发人员能够善用模版设计的并不多.模版设计这个好物,一般还有一个名称,就是 ...