Word Ladder----leetcode
来源:互联网 发布:程序员培训 编辑:程序博客网 时间:2024/06/06 00:22
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字符串不要求属于字典,但是变换的中间字符串必须存在于字典并且只能出现一次(很关键,题目中没有明显表述,但是确实是如此),每次变换只能改变字符串中的一个单词,这里所有的讨论包括字典都只考虑小写字母。
是广度搜索(BFS)的变型,可以进行一层的搜索,distance加1,直到找到end为止。代码如下:
public class Solution { public int ladderLength(String start, String end, HashSet<String> dict) { HashSet<String> set=new HashSet<String>(); Queue<String> queue=new LinkedList<String>(); queue.offer(start); set.add(start); int distance=1; while(!queue.isEmpty()) { int count=queue.size(); while(count>0) { char[] tempstr=queue.poll().toCharArray(); for(int i=0;i<tempstr.length;i++) { char tempchar=tempstr[i]; for(char c='a';c<='z';c++) { if(c==tempchar) continue; tempstr[i]=c; String str=new String(tempstr); if(str.equals(end)) return distance+1; if(dict.contains(str)&&!set.contains(str)) { queue.offer(str); set.add(str); } } tempstr[i]=tempchar; } count--; } distance++; } return 0; }}
0 0
- [Leetcode][python]Word Ladder/Word Ladder II
- [Leetcode] Word Ladder
- LeetCode: Word Ladder
- leetcode 84: Word Ladder
- [leetcode] word ladder
- 【leetcode】Word Ladder
- 【leetcode】Word Ladder II
- LeetCode - Word Ladder
- LeetCode之Word Ladder
- [LeetCode]Word Ladder
- [LeetCode]Word Ladder II
- [Leetcode]Word Ladder
- [leetcode]Word Ladder
- [leetcode] Word Ladder
- [leetcode] Word Ladder II
- LeetCode-Word Ladder
- LeetCode- Word Ladder
- LeetCode - Word Ladder II
- 关于cvCreateFileCapture()读取视频文件失败的解决记录
- Myeclipse maven创建webapp
- sql server 2008 不允许保存更改,您所做的更改要求删除并重新创建以下表 的解决办法
- linux 下搭建java web环境
- iOS7—Day by day—Day9:Device Identification
- Word Ladder----leetcode
- 总结
- textarea内容不为空的问题
- Java产生随机数
- <script>标签的for和event属性
- 关系操作
- 拦截QT关闭窗口的CloseEvent()解析
- notepad++ xml---如何使用Notepad++格式化XML文件
- EF架构封装类