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用来记录当前词典中的单词,做一个单词变换生成一个新单词,都需要判断这个单词是否在词典中,不 ...
随机推荐
- Python实现双色球和大乐透摇奖
实现代码: # code by kadycui # 模块引用 import random def select(): print('\n') print('请选择彩票种类') print('双色球输入 ...
- 【BZOJ 3326】[Scoi2013]数数 数位dp+矩阵乘法优化
挺好的数位dp……先说一下我个人的做法:经过观察,发现这题按照以往的思路从后往前递增,不怎么好推,然后我就大胆猜想,从前往后推,发现很好推啊,维护四个变量,从开始位置到现在有了i个数 f[i]:所有数 ...
- 用vim去掉utf-8 BOM
'去掉utf-8 BOM :set nobomb '保留utf-8 BOM :set bomb
- 【刷题】BZOJ 3524 [Poi2014]Couriers
Description 给一个长度为n的序列a.1≤a[i]≤n. m组询问,每次询问一个区间[l,r],是否存在一个数在[l,r]中出现的次数大于(r-l+1)/2.如果存在,输出这个数,否则输出0 ...
- [洛谷P4091][HEOI2016/TJOI2016]求和
题目大意:给你$n(n\leqslant10^5)$,求:$$\sum\limits_{i=0}^n\sum\limits_{j=0}^i\begin{Bmatrix}i\\j\end{Bmatrix ...
- BZOJ3835 [Poi2014]Supercomputer 【斜率优化】
题目链接 BZOJ3835 题解 对于\(k\),设\(s[i]\)为深度大于\(i\)的点数 \[ans = max\{i + \lceil \frac{s[i]}{k}\} \rceil\] 最优 ...
- ppp协议介绍(转)
原文:https://www.cnblogs.com/gtarcoder/p/6259105.html PPP协议PPP协议是二层(数据链路层)协议,常用于拨号上网时客户端向服务器获取IP地址.PPP ...
- Service Fabric Cluster Manager
作者:潘罡 (Van Pan)@ Microsoft 我们回到Service Fabric最底层的话题,谈谈Service Fabric是怎么工作的. 首先,我们回到下面的文档,看看Service F ...
- Redis学习七:Redis的持久化-总结(Which one)
1.官网建议 2.RDB持久化方式能够在指定的时间间隔能对你的数据进行快照存储 3.AOF持久化方式记录每次对服务器写的操作,当服务器重启的时候会重新执行这些 命令来恢复原始的数据,AOF命令以red ...
- VBscript.Encode 解码器
VBscript.Encode 解码器 此解码器算法来至互联网,我只是收集然后写了个简单的页面便于大家使用. 如有何不妥之处,请留言.