Word Ladder I & II
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:
- Only one letter can be changed at a time
- 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.
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的更多相关文章
- LeetCode:Word Ladder I II
其他LeetCode题目欢迎访问:LeetCode结题报告索引 LeetCode:Word Ladder Given two words (start and end), and a dictiona ...
- 【leetcode】Word Ladder II
Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation ...
- 18. Word Ladder && Word Ladder II
Word Ladder Given two words (start and end), and a dictionary, find the length of shortest transform ...
- LeetCode :Word Ladder II My Solution
Word Ladder II Total Accepted: 11755 Total Submissions: 102776My Submissions Given two words (start ...
- [leetcode]Word Ladder II @ Python
[leetcode]Word Ladder II @ Python 原题地址:http://oj.leetcode.com/problems/word-ladder-ii/ 参考文献:http://b ...
- LeetCode: Word Ladder II 解题报告
Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation s ...
- [Leetcode Week5]Word Ladder II
Word Ladder II 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/word-ladder-ii/description/ Descripti ...
- 126. Word Ladder II(hard)
126. Word Ladder II 题目 Given two words (beginWord and endWord), and a dictionary's word list, find a ...
- leetcode 127. Word Ladder、126. Word Ladder II
127. Word Ladder 这道题使用bfs来解决,每次将满足要求的变换单词加入队列中. wordSet用来记录当前词典中的单词,做一个单词变换生成一个新单词,都需要判断这个单词是否在词典中,不 ...
随机推荐
- elasticsearch使用More like this实现基于内容的推荐
基于内容的推荐通常是给定一篇文档信息,然后给用户推荐与该文档相识的文档.Lucene的api中有实现查询文章相似度的接口,叫MoreLikeThis.Elasticsearch封装了该接口,通过Ela ...
- nginx支持.htaccess文件实现伪静态的方法
方法如下: 1. 在需要使用.htaccess文件的目录下新建一个.htaccess文件, vim /var/www/html/.htaccess 2. 在里面输入规则,我这里输入Discuz的伪静态 ...
- In Place Algorithm
本篇是in place algorithm的学习笔记.目前学习的是in place merge与in place martrix transposition这两个算法. 1.in place merg ...
- 【刷题】BZOJ 1537 [POI2005]Aut- The Bus
Description Byte City 的街道形成了一个标准的棋盘网络 – 他们要么是北南走向要么就是西东走向. 北南走向的路口从 1 到 n编号, 西东走向的路从1 到 m编号. 每个路口用两个 ...
- 【刷题】BZOJ 1969 [Ahoi2005]LANE 航线规划
Description 对Samuel星球的探险已经取得了非常巨大的成就,于是科学家们将目光投向了Samuel星球所在的星系--一个巨大的由千百万星球构成的Samuel星系. 星际空间站的Samuel ...
- linux内核分析 第七周读书笔记
第七章 链接 1.链接是将各种代码和数据部分收集起来并组合成为一个单一文件的过程,这个文件可被加载到存储器并执行. 2.链接可以执行于编译时,加载时,运行时. 7.1编译器驱动程序 1.大多数编译系统 ...
- APK反编译之二:工具介绍
前面一节我们说过,修改APK最终是通过修改smali来实现的,所以我们接下来介绍的工具就是如何把APK中的smali文件获取出来,当然同时也需要得到AndroidManifest.xml等文件.直接修 ...
- struts2为什么action要继承actionSupport类
我们为了方便实现Action,大多数情况下都会继承com.opensymphony.xwork2.ActionSupport类, 并重载(Override)此类里的String execute()方法 ...
- Memcache PHP 使用笔记
Memcache PHP 使用笔记 最近在做网站迁移 看到之前的一个网站目录下Cache文件里上万的缓存文件真是害怕 新的服务器上配置了memcache扩展 于是乎准备折腾一下看看能不能把之前的文件缓 ...
- Unity官方实例教程 Roll-a-Ball
与unity的transform组件相处的挺久了,最近项目不太忙,决定好好打下unity的基础.那么从Roll-a-Ball这个简单游戏开始吧! 1.先创建一个球体游戏对象,改名为Player,tra ...