leetcode 126. Word Ladder II ----- java
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the word list
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
Return
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
Note:
- All words have the same length.
- All words contain only lowercase alphabetic characters.
从start变换到end,途中只能经过字典中的单词,每次只允许差一个字母。
要求输出所有最短变换路径。
这里刚开始使用了最普通的方法,即利用DFS,超时了。
public class Solution {
List list = new ArrayList<List>();
int num = 0;
String[] words;
String[] ans;
public List<List<String>> findLadders(String beginWord, String endWord, Set<String> wordList) {
if( beginWord.length() == 0 || wordList.size() == 0 )
return list;
int len = wordList.size();
words = new String[len];
int i = 0;
for( String str : wordList ){
words[i] = str;
i++;
}
ans = new String[len+2];
ans[0] = beginWord;
helper(beginWord,endWord,1);
return list;
}
public void helper(String beginWord,String endWord,int pos){
if( OneDiff(beginWord,endWord)){
if( num == 0 )
num = pos;
else if( num < pos )
return;
else if( num > pos ){
list.clear();
num = pos;
}
List ll = new ArrayList<String>();
for( int i = 0;i<pos;i++)
ll.add(ans[i]);
ll.add(endWord);
list.add(ll);
return ;
}
for( int i = 0;i<words.length;i++){
String str = words[i];
if( str == "-1")
continue;
if( OneDiff(beginWord,str) ){
ans[pos] = str;
words[i] = "-1";
helper(str,endWord,pos+1);
words[i] = str;
}
}
}
public boolean OneDiff(String word1,String word2){
int flag = 0;
for( int i = 0;i<word1.length();i++){
if( word1.charAt(i) == word2.charAt(i) )
continue;
else{
if( flag == 0)
flag =1;
else
return false;
}
}
return true;
}
}
}
2、使用BFS,仍旧超时了。
public class Solution {
List list = new ArrayList<List>();
Queue queue;
HashMap map = new HashMap<String,Integer>();
public List<List<String>> findLadders(String beginWord, String endWord, Set<String> wordList) {
if( beginWord.length() == 0 || wordList.size() == 0 )
return list;
queue = new LinkedList<ArrayList<String>>();
if( OneDiff(beginWord,endWord) ){
List ll = new ArrayList<String>();
ll.add(beginWord);
ll.add(endWord);
list.add(ll);
return list;
}
List ll = new ArrayList<String>();
ll.add(beginWord);
int flag = 0;
int deep = 0;
map.put(beginWord,deep);
queue.add(ll);
while( !queue.isEmpty() ){
deep++;
int len = queue.size();
for( int i = 0;i<len;i++) {
List l1 = (List) queue.poll();
String s1 = (String) l1.get(l1.size() - 1);
for (String str : wordList) {
if (OneDiff(s1, str) && ( !map.containsKey(str) || (int)map.get(str) == deep) ) {
map.put(str,deep);
List l2 = new ArrayList<String>();
l2.addAll(l1);
l2.add(str);
queue.add(l2);
if (OneDiff(str, endWord)) {
l2.add(endWord);
// for (int ii = 0; ii < l2.size(); ii++)
// System.out.print(l2.get(ii) + " ");
// System.out.println();
list.add(l2);
flag = 1;
}
}
}
}
if( flag == 1)
queue.clear();
}
return list;
}
public boolean OneDiff(String word1,String word2){
int flag = 0;
for( int i = 0;i<word1.length();i++){
if( word1.charAt(i) == word2.charAt(i) )
continue;
else{
if( flag == 0)
flag++;
else
return false;
}
}
if( flag == 1)
return true;
else
return false;
}
}
3、借鉴了他人的答案
优化方法:先BFS生成找到end时的生成树,标记出每个单词所在的层数。然后从目标用DFS往回找,过了大数据。
NOTE:我在代码中刚开始由于存在static,导致测试用例一直无法通过。
public class Solution {
List list = new ArrayList<List>();
HashMap map = new HashMap<String,Integer>();
public List<List<String>> findLadders(String beginWord, String endWord, Set<String> wordList) {
if( beginWord == null || beginWord.length() == 0 || wordList.size() == 0 || beginWord.length() != endWord.length() )
return list;
BFS(beginWord,endWord,wordList);
if( map.size()== 1 )
return list;
DFS(endWord,beginWord,new ArrayList<String>());
return list;
}
public void DFS(String beginWord,String endWord,List ans){
if( beginWord.equals(endWord) ){
ans.add(beginWord);
Collections.reverse(ans);
list.add(ans);
return ;
}
if( map.get(beginWord) == null )
return ;
ans.add(beginWord);
int deep = (int) map.get(beginWord)-1;
for( int i = 0;i<beginWord.length();i++){
char[] word = beginWord.toCharArray();
for( char ch = 'a';ch<='z';ch++) {
word[i] = ch;
String nWord = new String(word);
if ( map.get(nWord) != null && ((int) map.get(nWord) == deep)) {
ArrayList ll = new ArrayList<String>(ans);
DFS(nWord, endWord, ll);
}
}
}
}
public void BFS(String beginWord,String endWord,Set<String> wordList){
Queue queue = new LinkedList<String>();
queue.add(beginWord);
map.put(beginWord,0);
while( !queue.isEmpty() ){
String str = (String) queue.poll();
if( str.equals(endWord) )
continue;
for( int i = 0 ;i <beginWord.length();i++){
char[] word = str.toCharArray();
for( char ch = 'a';ch<='z';ch++) {
word[i] = ch;
String Nword = new String(word);
if ( Nword.equals(endWord) || wordList.contains(Nword)) {
if (!map.containsKey(Nword)) {
map.put(Nword, (int) map.get(str) + 1);
queue.add(Nword);
}
}
}
}
}
}
}
leetcode 126. Word Ladder II ----- java的更多相关文章
- Java for LeetCode 126 Word Ladder II 【HARD】
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- LeetCode 126. Word Ladder II 单词接龙 II(C++/Java)
题目: Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transfo ...
- [LeetCode] 126. Word Ladder II 词语阶梯 II
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...
- [LeetCode] 126. Word Ladder II 词语阶梯之二
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...
- Leetcode#126 Word Ladder II
原题地址 既然是求最短路径,可以考虑动归或广搜.这道题对字典直接进行动归是不现实的,因为字典里的单词非常多.只能选择广搜了. 思路也非常直观,从start或end开始,不断加入所有可到达的单词,直到最 ...
- leetcode@ [126] Word Ladder II (BFS + 层次遍历 + DFS)
https://leetcode.com/problems/word-ladder-ii/ Given two words (beginWord and endWord), and a diction ...
- leetcode 127. Word Ladder、126. Word Ladder II
127. Word Ladder 这道题使用bfs来解决,每次将满足要求的变换单词加入队列中. wordSet用来记录当前词典中的单词,做一个单词变换生成一个新单词,都需要判断这个单词是否在词典中,不 ...
- 126. Word Ladder II(hard)
126. Word Ladder II 题目 Given two words (beginWord and endWord), and a dictionary's word list, find a ...
- [Leetcode Week5]Word Ladder II
Word Ladder II 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/word-ladder-ii/description/ Descripti ...
随机推荐
- [开发笔记]-Visual Studio 2012中为创建的类添加注释的模板
为类文件添加注释,可以让我们在写代码时能够方便的查看这个类文件是为了实现哪些功能而写的. 一:修改类文件模板 找到类模版的位置:C:\Program Files (x86)\Microsoft Vis ...
- struts2 类型转换
概述 从一个 HTML 表单到一个 Action 对象, 类型转换是从字符串到非字符串. 在 struts2 中, 把请求参数映射到 action 属性的工作由 Parameters 拦截器负责, ...
- Windows任务计划
任务计划,可以将任何脚本.程序或文档安排在某个时间运行.“任务计划”在每次启动windows系统的时候自动启动(默认Task Scheduler服务是开启的)并在后台运行.使用“任务计划”可以完成以下 ...
- Flux Demo解析
最近学习了阮一峰老师的博文 "Flux入门教程",博文中详细介绍了Flux框架和Controller view模式,并提供了Demo,受益匪浅. 现特参考阮老师的Demo,绘制了一 ...
- Spring学习笔记之模块简介
1.Core Container(Application context) module 这个是Spring最基本的模块,它提供了spring框架最基本的功能.BeanFactory 是任何基于Spr ...
- 创建plist文件
可以先在工程中直接新建一个plist文件,往里面写入自己需要的数据.但是这里的plist文件我们无法修改,是只读的,我们可以将这个plist文件复制一份到沙盒中,然后对沙盒中的文件进行操作.具体代码如 ...
- Oracle GoldenGate 12c (12.1.2.0.1) for IBM DB2 iSeries
OGG 12.1.2.0.1 for iSeries 在2014.2.15发布,主要新增如下功能: 本地交付(Native Delivery Replicat):新功能允许用户在IBM i服务器上安装 ...
- Tomcat的目录结构(二)
一.Tomcat的目录结构 bin:启动和关闭Tomcat的bat文件 conf:配置文件 server.xml:配置和server相关的信息,比如:Tomcat启动的端口号,配置Host,配置Con ...
- 一篇很好介绍stringBuffer和StringBuilder的区别--来自百度
ava.lang.StringBuffer线程安全的可变字符序列.一个类似于 String 的字符串缓冲区,但不能修改.虽然在任意时间点上它都包含某种特定的字符序列,但通过某些方法调用可以改变该序列的 ...
- sql连接又一篇
作者:初行 – 博客园 SQL连接可以分为内连接.外连接.交叉连接. 数据库数据: book表: stu表: ...