Word Ladder I

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
Notice
  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
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.

分析:

BFS。但是下面这种发现现在通不过了,所以得想其它方法

 public class Solution {

     public int ladderLength(String start, String end, Set<String> dict) {
if (diff(start, end) == ) return ;
if (diff(start, end) == ) return ; ArrayList<String> inner = new ArrayList<String>();
ArrayList<String> outer = new ArrayList<String>();
inner.add(start);
int counter = ;
while (inner.size() != ) {
counter++;
if (dict.size() == ) return ;
for (int i = ; i < inner.size(); i++) {
ArrayList<String> dicts = new ArrayList<String>(dict);
for (int j = ; j < dicts.size(); j++) {
if (diff(inner.get(i), dicts.get(j)) == ) {
outer.add(dicts.get(j));
dict.remove(dicts.get(j));
}
}
} for (int k = ; k < outer.size(); k++) {
if (diff(outer.get(k), end) <= ) {
return counter + ;
}
} ArrayList<String> temp = inner;
inner = outer;
outer = temp;
outer.clear();
}
return ;
} private int diff(String start, String end) {
int total = ;
for (int i = ; i < start.length(); i++) {
if (start.charAt(i) != end.charAt(i)) {
total++;
}
}
return total;
}
}

第二种方法:递归,复杂度更高。

 public class Solution {
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
set.add("hot");
set.add("dot");
set.add("dog");
set.add("lot");
set.add("log"); Solution s = new Solution();
System.out.println(s.ladderLength("hit", "cog", set));
} public List<List<String>> ladderLength(String begin, String end, Set<String> set) { List<String> list = new ArrayList<String>();
List<List<String>> listAll = new ArrayList<List<String>>();
Set<String> used = new HashSet<String>();
helper(begin, end, list, listAll, used, set);
return listAll;
} // find out all possible solutions
public void helper(String current, String end, List<String> list, List<List<String>> listAll, Set<String> used,
Set<String> set) {
list.add(current);
used.add(current); if (diff(current, end) == ) {
ArrayList<String> temp = new ArrayList<String>(list);
temp.add(end);
listAll.add(temp);
} for (String str : set) {
if (!used.contains(str) && diff(current, str) == ) {
helper(str, end, list, listAll, used, set);
}
}
list.remove(current);
used.remove(current);
} // return the # of letters difference
public int diff(String word1, String word2) { int count = ;
for (int i = ; i < word1.length(); i++) {
if (word1.charAt(i) != word2.charAt(i)) {
count++;
}
}
return count;
}
}

方法3

 class Solution {
public int ladderLength(String begin, String end, List<String> list) {
Set<String> set = new HashSet<>(list);
if (!set.contains(end)) return ;
Queue<String> queue = new LinkedList<>();
int level = ;
queue.add(begin);
while (queue.size() != ) {
level++;
int size = queue.size();
for (int k = ; k <= size; k++) {
String word = queue.poll();
char[] chs = word.toCharArray();
for (int i = ; i < chs.length; i++) {
char ch = chs[i];
for (char temp = 'a'; temp <= 'z'; temp++) {
chs[i] = temp;
String tempStr = new String(chs);
if (tempStr.equals(end)) return level + ;
if (set.contains(tempStr)) {
set.remove(tempStr);
queue.offer(tempStr);
}
}
chs[i] = ch;
}
}
}
return ;
}
}

Word Ladder II

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", and dict = ["hot","dot","dog","lot","log"], return:

  [
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]

分析:

原理同上,按照层进行递进,当最外层到达end以后,我们就退出。

 class Solution {
public List<List<String>> findLadders(String start, String end, List<String> dictList) {
List<List<String>> result = new ArrayList<>();
boolean hasFound = false;
Set<String> dict = new HashSet<>(dictList);
Set<String> visited = new HashSet<>();
if (!dict.contains(end)) {
return result;
}
Queue<Node> candidates = new LinkedList<>();
candidates.offer(new Node(start, null));
while (!candidates.isEmpty()) {
int count = candidates.size();
if (hasFound) return result;
for (int k = ; k <= count; k++) {
Node node = candidates.poll();
String word = node.word;
char[] chs = word.toCharArray();
for (int i = ; i < chs.length; i++) {
char temp = chs[i];
for (char ch = 'a'; ch <= 'z'; ch++) {
chs[i] = ch;
String newStr = new String(chs);
if (dict.contains(newStr)) {
visited.add(newStr);
Node newNode = new Node(newStr, node);
candidates.add(newNode);
if (newStr.equals(end)) {
hasFound = true;
List<String> path = getPath(newNode);
result.add(path);
}
}
}
chs[i] = temp;
}
}
dict.removeAll(visited);
}
return result;
} private List<String> getPath(Node node) {
List<String> list = new LinkedList<>();
while (node != null) {
list.add(, node.word);
node = node.pre;
}
return list;
}
} class Node {
String word;
Node pre; public Node(String word, Node pre) {
this.word = word;
this.pre = pre;
}
}

Word Ladder I & II的更多相关文章

  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

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

  3. 18. Word Ladder && Word Ladder II

    Word Ladder Given two words (start and end), and a dictionary, find the length of shortest transform ...

  4. LeetCode :Word Ladder II My Solution

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

  5. [leetcode]Word Ladder II @ Python

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

  6. LeetCode: Word Ladder II 解题报告

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

  7. [Leetcode Week5]Word Ladder II

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

  8. 126. Word Ladder II(hard)

    126. Word Ladder II 题目 Given two words (beginWord and endWord), and a dictionary's word list, find a ...

  9. leetcode 127. Word Ladder、126. Word Ladder II

    127. Word Ladder 这道题使用bfs来解决,每次将满足要求的变换单词加入队列中. wordSet用来记录当前词典中的单词,做一个单词变换生成一个新单词,都需要判断这个单词是否在词典中,不 ...

随机推荐

  1. DAY3-Python学习笔记

    1.元类:动态语言和静态语言最大的不同,就是函数和类的定义,不是编译时定义的,而是运行时动态创建的,不是定义死了,而是可以随时随地添加的 type():查看一个类型或变量的类型又可以创建出新的类型 c ...

  2. MT【150】源自斐波那契数列

    (清华2017.4.29标准学术能力测试7) 已知数列$\{x_n\}$,其中$x_1=a$,$x_2=b$,$x_{n+1}=x_n+x_{n-1}$($a,b$是正整数),若$2008$为数列中的 ...

  3. jQuery map和each用法

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  4. 文件查找 locate 和 find

    locate locate命令依赖于一个数据库文件,系统默认每天会检索一次系统中的所有文件,然后将检索到的文件记录到数据库中; 在执行查找时,可直接到数据库中查找记录,所以locate比find反馈更 ...

  5. Java之Junit和反射

    Junit,反射 Junit 1.测试的分类: 黑盒测试 : 不需要写代码,给输入值,看程序是否能够输出期望的值. 白盒测试 : 需要进行代码的编写,关注的是程序的具体流程. 2.使用步骤(方法类的命 ...

  6. Andrioid Studio生成jar, aar包

    在Android Studio中对一个自己库进行生成操作时将会同时生成*.jar与*.aar文件.分别存储位置:*.jar:库/build/intermediates/bundles/debug(re ...

  7. python检测服务器是否ping通

    好想在2014结束前再赶出个10篇博文来,~(>_<)~,不写博客真不是一个好兆头,至少说明对学习的欲望和对知识的研究都不是那么积极了,如果说这1天的时间我能赶出几篇精致的博文,你们信不信 ...

  8. Dubbo、Zookeeper集群搭建及Rose使用心得(二)

    上篇讲了一下配置,这次主要写一下这个框架开发的大概流程.这里以实现 登陆 功能为例. 一.准备工作 1.访问拦截器 用户在进行网站访问的时候,有可能访问到不存在的网页,所以,我们需要把这些链接重新定向 ...

  9. lumen 单元测试的一些问题

    1.一个 test 多个请求 如 $this->post,然后又  $this->post,我们会发现第二个请求中的请求参数是和第一个请求的参数是完全一样的,然后在 Controller ...

  10. golang json 编码解码

    json 编码 package main import ( "encoding/json" "fmt" ) type Person struct { Name ...