[LeetCode][Java] Word Ladder
2015-07-28 15:43
399 查看
题目:
Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord,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.
题意:
给定两个单词(开始单词 和 结束单词)和一个字典。找出从开始单词到结束单词最短的转换序列的长度。注意:
1. 每次只能改变一个字母。
2. 每一个中间的单词必须是字典中的。
例如:
给定:
start =
"hit"
end =
"cog"
dict =
["hot","dot","dog","lot","log"]
其中一个最短的转化为
"hit" -> "hot" -> "dot" -> "dog" -> "cog",
返回的长度为5.
注意:
1.如果不存在该转化序列,就返回0.
2.所有的单词具有相等的长度.
3.所有的单词都是小写.
算法分析:
这道题是套用BFS同时也利用BFS能寻找最短路径的特性来解决问题。把每个单词作为一个node进行BFS。当取得当前字符串时,对他的每一位字符进行从a~z的替换,如果在字典里面,就入队,并将下层count++,并且为了避免环路,需把在字典里检测到的单词从字典里删除。这样对于当前字符串的每一位字符安装a~z替换后,在queue中的单词就作为下一层需要遍历的单词了。
正因为BFS能够把一层所有可能性都遍历了,所以就保证了一旦找到一个单词equals(end),那么return的路径肯定是最短的。
---类似于层序遍历二叉树,找到最先遍历到的叶子的层数就是树的最小高度;在该题中BFS遍历找到的第一个匹配就是最短转换,
逐层挨个遍历,第一次遍历到的结束节点,当然是最短的路径
AC代码:
<span style="font-family:Microsoft YaHei;font-size:12px;">public class Solution { public int ladderLength(String start, String end, Set<String> dict) { if(start==null || end==null || start.length()==0 || end.length()==0 || start.length()!=end.length()) return 0; LinkedList<String> wordQueue = new LinkedList<String>(); int level = 1; //定义当前的层级 int curnum = 1;//定义当前层的节点数 int nextnum = 0;//定义下一层的节点数 wordQueue.add(start); while(!wordQueue.isEmpty()) { String word = wordQueue.poll(); curnum--; for(int i = 0; i < word.length(); i++) { char[] wordunit = word.toCharArray(); for(char j = 'a'; j <= 'z'; j++) { wordunit[i] = j; String temp = new String(wordunit); if(temp.equals(end)) return level+1; if(dict.contains(temp)) { wordQueue.add(temp); nextnum++; dict.remove(temp); } } } if(curnum == 0)//说明该层访问结束,需要进入下一层 { curnum = nextnum; nextnum = 0; level++; } } return 0; } }</span>
相关文章推荐
- eclipse 报错:GC overhead limit exceeded
- 猴子背100根香蕉问题程序实现
- Spring-SpringJdbcTemlate配置介绍
- 浅谈JAVA中反射机制
- Java:重写equals()和hashCode()
- 几个著名Java开源缓存框架介绍(OSCache,JSC)
- Java main方法
- springmvc 使用ajax报406错误
- java中实现多线程
- spring mvc 后台获取不到form提交的参数
- Java中多态、抽象类和接口
- Java中文档制作与继承
- [Windows]在Win7系统下搭建Eclipse+Cygwin开发环境
- Java中反射与正则小结
- Spring DI 集合属性依赖注入
- 比较Java Swing中三种注册事件的方法
- 常用正则表达式 -- 费元星 java大神
- Java中面向对象的详解
- Java学习笔记3:Java编程中字符串的处理
- Spring DI 属性注入深入——P名称空间和spEL表达式