Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, 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"
dict = ["hot","dot","dog","lot","log"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

解题思路一:

对set进行逐个遍历,递归实现,JAVA实现如下:

	static public int ladderLength(String beginWord, String endWord,
Set<String> wordDict) {
int result = wordDict.size() + 2;
Set<String> set = new HashSet<String>(wordDict);
if (oneStep(beginWord, endWord))
return 2;
for (String s : wordDict) {
if (oneStep(beginWord, s)) {
set.remove(s);
int temp = ladderLength(s, endWord, set);
if (temp != 0)
result = Math.min(result, temp + 1);
set.add(s);
}
}
if (result == wordDict.size() + 2)
return 0;
return result;
} public static boolean oneStep(String s1, String s2) {
int res = 0;
for (int i = 0; i < s1.length(); i++)
if (s1.charAt(i) != s2.charAt(i))
res++;
return res == 1;
}

结果TLE

解题思路二:

发现直接遍历是行不通的,实际上如果使用了oneStep函数,不管怎么弄都会TLE的(貌似在C++中可以AC)。

本题的做法应该是采用图的BFS来做,同时oneStep的匹配也比较有意思,JAVA实现如下:

static public int ladderLength(String start, String end, Set<String> dict) {
HashMap<String, Integer> disMap = new HashMap<String, Integer>();
LinkedList<String> queue = new LinkedList<String>();
queue.add(start);
disMap.put(start, 1);
while (!queue.isEmpty()) {
String word = queue.poll();
for (int i = 0; i < word.length(); i++) {
for (char ch = 'a'; ch <= 'z'; ch++) {
StringBuilder sb = new StringBuilder(word);
sb.setCharAt(i, ch);
String nextWord = sb.toString();
if (end.equals(nextWord))
return disMap.get(word) + 1;
if (dict.contains(nextWord) && !disMap.containsKey(nextWord)) {
disMap.put(nextWord, disMap.get(word) + 1);
queue.add(nextWord);
}
}
}
}
return 0;
}

最新文章

  1. bzoj2693--莫比乌斯反演+积性函数线性筛
  2. ImportError: No module named &#39;requests&#39;
  3. Lintcode 75.寻找峰值
  4. Python_Day_01(使用环境为Python3.0+)
  5. iOS UIButton 设置图片不变型setImage
  6. 非阻塞同步算法与CAS(Compare and Swap)无锁算法
  7. Leetcode: Largest BST Subtree
  8. iOS用ASIHttpRequest上传
  9. C#控制管理VisualSVN Server 分类: C# 2014-05-29 15:51 796人阅读 评论(0) 收藏
  10. Log Parser 2.2
  11. android 开发edittext获取焦点时hint消失
  12. fopen vs fsocketopen vs curl
  13. 对于shell脚本参数获取时的一点小技巧
  14. Implement Stack using Queues ——LeetCode
  15. 创建DBLink语句
  16. Azure构建PredictionIO和Spark的推荐引擎服务
  17. Python程序员为什么一定要掌握Linux?
  18. Linux 问题
  19. Android获取手机号码
  20. Centos 7 KVM安装win10

热门文章

  1. 详解UIView的frame、bounds和center属性
  2. MVC4 Task.Factory.StartNew 异步调用
  3. Vagrant + PHPStorm 使用 Xdebug
  4. MFC中 编辑框输入换行功能
  5. Mysql的时间戳转date类型
  6. 2017.2.21 Java中正则表达式的学习及示例
  7. mysql 远程登陆不上
  8. mongodb springdata 问题处理
  9. 身份证号码 javascript 验证
  10. 【强网杯2018】Gamebox