[Leetcode][JAVA] Word Ladder
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
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.
乍看起来很难的一题,其实仔细分析就是图的遍历。把start,end和dict里的词都看作一个个结点,如果一个词可以合法转化为另一个词,那么视为这两个“结点”中间有一条路径。问题则变为,找到从start到end的最短路径长度。
如果采用扫描所有dict中单词,然后判断是否合法来遍历结点的方法,会超时(因为有dict中单词过多的用例)。所以只能采用别的遍历思路。
一个有效的遍历思路是获取到当前单词长度,然后对每一位都尝试替换为别的字符来遍历,即得到所以可能的合法字符串,然后判断是否等于end,或者在dict中且不在已遍历过的结点中,这样时间复杂度就是O(l)仅仅跟单词长度有关了。
对每一个结点,都用HashMap保存start到它的路径长度,新结点进入时只需要把长度加一即可。
采用广度优先遍历比较好,因为我们只需要获得最短的路径长度,而广度优先可以保证第一个到达end的路径是最短的(即到达end即可以return)。
代码如下:
public int ladderLength(String start, String end, Set<String> dict) {
HashMap<String, Integer> hm = new HashMap<String, Integer>();
Queue<String> q = new LinkedList<String>();
q.add(start);
hm.put(start,1);
while(!q.isEmpty())
{
String temp = q.poll();
int len = hm.get(temp);
for(int i=0;i<temp.length();i++) {
for(char c='a';c<='z';c++) {
if(c==temp.charAt(i))
continue;
StringBuilder sb = new StringBuilder(temp);
sb.setCharAt(i,c);
String next = sb.toString();
if(next.equals(end))
return len+1;
if(dict.contains(next) && !hm.containsKey(next)) {
q.add(next);
hm.put(next,len+1);
}
}
}
}
return 0;
}
[Leetcode][JAVA] Word Ladder的更多相关文章
- [Leetcode][JAVA] Word Ladder II
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- 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] 127. Word Ladder 单词阶梯
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...
- LeetCode 127. Word Ladder 单词接龙(C++/Java)
题目: Given two words (beginWord and endWord), and a dictionary's word list, find the length of shorte ...
- [LeetCode#128]Word Ladder II
Problem: Given two words (start and end), and a dictionary, find all shortest transformation sequenc ...
- [Leetcode Week5]Word Ladder II
Word Ladder II 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/word-ladder-ii/description/ Descripti ...
- [Leetcode Week5]Word Ladder
Word Ladder题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/word-ladder/description/ Description Give ...
随机推荐
- Karma:2. 集成 Karma 和 mocha 进行单元测试
上一篇文章讨论了如何集成 Karma 和 Jasmine,地址见:Karma:1. 集成 Karma 和 Jasmine 进行单元测试 这篇文章讨论如何 Karma 集成 mocha 测试框架. 安装 ...
- VS2010 项目引用了DLL文件,也写了Using,但是编译时提示:未能找到类型或命名空间名称 <转>
昨天写了一个很小的winform程序,其中引用了自己写的两个dll文件. 本来认为轻松搞定,结果一编译居然提示:未能找到类型或命名空间名称..... 于是删掉两个dll重新引用,再编译结果依旧!很是郁 ...
- Linux学习笔记——查看Linux系统信息的方法
由于Linux的发行版本比较多,并且有些差异性,所以,分析问题时我们常常需要知道自己的Linux系统的版本信息,以下是我搜集到的一些方法 1:显示电脑以及操作系统的相关信息 qian@ubuntu:~ ...
- 8,SFDC 管理员篇 - 数据模型 - 公式和验证 2
1, Checkbox 只接受真值或者假值 And(arg1, arg2....)至少两个参数,只有参数都为真时候,才返回真,只要有一个为假,就都为假 例如:AND(DoNotCall, HasOpt ...
- 纸上谈兵:队列(queue)
作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 队列(queue)是一个简单而常见的数据结构.队列也是有序的元素集合.队列最大的特 ...
- Servlet的过滤器Filter
Servlet 编写过滤器 Servlet 过滤器可以动态地拦截请求和响应,以变换或使用包含在请求或响应中的信息. 可以将一个或多个 Servlet 过滤器附加到一个 Servlet 或一组 Serv ...
- VHDL 学习
近期在接触 VHDL,首先要本好书,个人觉得 1)<VHDL for engineer> VHDL 大学实用教程 (这个名字翻译的无语...) 2)估计verilog的作者的 bhask ...
- ComponentCount 与 ControlCount 区别
ShowMessage(panel.ComponentCount.ToString); ShowMessage(panel.ControlCount.ToString);componetcou ...
- BCB中获得RichEdit 默认行间距
首先,这些功能支持RichEdit2.0 以上功能: 其次,用常规的方法是无法获得LineSpace 的: 你使用 EM_GETPARAFORMAT也得不到,你会发现dyLineSpacing 的值永 ...
- 解决PHP在IE中下载文件,中文文件名乱码问题
if( stripos($_SERVER['HTTP_USER_AGENT'], 'MSIE')!==false ) $filename = urlencode( $filename ); // 输入 ...