作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址: https://leetcode.com/problems/word-ladder/description/

题目描述:

Given two words (beginWord and endWord), and a dictionary’s word list, 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 transformed word must exist in the word list. Note that beginWord is not a transformed word.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
  • You may assume no duplicates in the word list.
  • You may assume beginWord and endWord are non-empty and are not the same.

Example 1:

  1. Input:
  2. beginWord = "hit",
  3. endWord = "cog",
  4. wordList = ["hot","dot","dog","lot","log","cog"]
  5. Output: 5
  6. Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
  7. return its length 5.

Example 2:

  1. Input:
  2. beginWord = "hit"
  3. endWord = "cog"
  4. wordList = ["hot","dot","dog","lot","log"]
  5. Output: 0

Explanation: The endWord “cog” is not in wordList, therefore no possible transformation.

题目大意

这个题名字是词语梯子,简单理解就是从begin开始,每次只能替换已经转化了的单词的其中一个字符,看最终能不能得到end。有个要求就是,每次变化不是任意的,是必须变成wordList中的其中一个才行。

解题方法

拿到这个题没有什么思路,看了别人解答之后,才猛然发现这个题是走迷宫问题的变形!也就是说,我们每次变化有26个方向,如果变化之后的位置在wordList中,我们认为这个走法是合规的,最后问能不能走到endWord?

很显然这个问题是BFS的问题,只是把走迷宫问题的4个方向转变成了26个方向,直接BFS会超时,所以我使用了个visited来保存已经遍历了的字符串,代表已经走过了的位置。代码总体思路很简单,就是利用队列保存每个遍历的有效的字符串,然后对队列中的每个字符串再次遍历,保存每次遍历的长度即可。

时间复杂度是O(NL),空间复杂度是O(N).其中N是wordList中的单词个数,L是其实字符串的长度。

  1. class Solution(object):
  2. def ladderLength(self, beginWord, endWord, wordList):
  3. """
  4. :type beginWord: str
  5. :type endWord: str
  6. :type wordList: List[str]
  7. :rtype: int
  8. """
  9. wordset = set(wordList)
  10. if endWord not in wordset:
  11. return 0
  12. visited = set([beginWord])
  13. chrs = [chr(ord('a') + i) for i in range(26)]
  14. bfs = collections.deque([beginWord])
  15. res = 1
  16. while bfs:
  17. len_bfs = len(bfs)
  18. for _ in range(len_bfs):
  19. origin = bfs.popleft()
  20. for i in range(len(origin)):
  21. originlist = list(origin)
  22. for c in chrs:
  23. originlist[i] = c
  24. transword = "".join(originlist)
  25. if transword not in visited:
  26. if transword == endWord:
  27. return res + 1
  28. elif transword in wordset:
  29. bfs.append(transword)
  30. visited.add(transword)
  31. res += 1
  32. return 0

显然上面的这个做法还是可以变短一点的,想起之前的二叉树的BFS的时候,会在每个节点入队列的时候同时保存了这个节点的深度,这样就少了一层对bfs当前长度的循环,可以使得代码变短。同时,学会了一个技巧,直接把已经遍历过的位置从wordList中删除,这样就相当于我上面的那个visited数组。下面这个代码很经典了,可以记住。

  1. class Solution(object):
  2. def ladderLength(self, beginWord, endWord, wordList):
  3. """
  4. :type beginWord: str
  5. :type endWord: str
  6. :type wordList: List[str]
  7. :rtype: int
  8. """
  9. wordset = set(wordList)
  10. bfs = collections.deque()
  11. bfs.append((beginWord, 1))
  12. while bfs:
  13. word, length = bfs.popleft()
  14. if word == endWord:
  15. return length
  16. for i in range(len(word)):
  17. for c in "abcdefghijklmnopqrstuvwxyz":
  18. newWord = word[:i] + c + word[i + 1:]
  19. if newWord in wordset and newWord != word:
  20. wordset.remove(newWord)
  21. bfs.append((newWord, length + 1))
  22. return 0

参考资料:

http://www.cnblogs.com/grandyang/p/4539768.html

日期

2018 年 9 月 29 日 —— 国庆9天长假第一天!

【LeetCode】127. Word Ladder 解题报告(Python)的更多相关文章

  1. [LeetCode] 127. Word Ladder 单词阶梯

    Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...

  2. leetcode 127. Word Ladder、126. Word Ladder II

    127. Word Ladder 这道题使用bfs来解决,每次将满足要求的变换单词加入队列中. wordSet用来记录当前词典中的单词,做一个单词变换生成一个新单词,都需要判断这个单词是否在词典中,不 ...

  3. Leetcode#127 Word Ladder

    原题地址 BFS Word Ladder II的简化版(参见这篇文章) 由于只需要计算步数,所以简单许多. 代码: int ladderLength(string start, string end, ...

  4. LeetCode 127. Word Ladder 单词接龙(C++/Java)

    题目: Given two words (beginWord and endWord), and a dictionary's word list, find the length of shorte ...

  5. leetcode@ [127] Word Ladder (BFS / Graph)

    https://leetcode.com/problems/word-ladder/ Given two words (beginWord and endWord), and a dictionary ...

  6. Java for LeetCode 127 Word Ladder

    Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformatio ...

  7. leetcode 127. Word Ladder ----- java

    Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...

  8. [leetcode]127. Word Ladder单词接龙

    Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...

  9. [LeetCode] 127. Word Ladder _Medium tag: BFS

    Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...

随机推荐

  1. Linux—ps -ef 命令输出信息的具体含义(显示所有正在运行的命令程序)

    linux 中使用 ps -ef 输出参数的具体含义 功能:显示所有正在运行的命令程序 UID: 说明该程序被谁拥有PID:就是指该程序的 IDPPID: 就是指该程序父级程序的 IDC: 指的是 C ...

  2. 自动化测试系列(三)|UI测试

    UI 测试是一种测试类型,也称为用户界面测试,通过该测试,我们检查应用程序的界面是否工作正常或是否存在任何妨碍用户行为且不符合书面规格的 BUG.了解用户将如何在用户和网站之间进行交互以执行 UI 测 ...

  3. Pytorch学习笔记08----优化器算法Optimizer详解(SGD、Adam)

    1.优化器算法简述 首先来看一下梯度下降最常见的三种变形 BGD,SGD,MBGD,这三种形式的区别就是取决于我们用多少数据来计算目标函数的梯度,这样的话自然就涉及到一个 trade-off,即参数更 ...

  4. mysql数据操作语言DML

    插入insert 插入方式1 语法: insert into 表名(列名,....) values(值1,....) 说明: 1.插入的值的类型要与列的类型一致或兼容 2.可以为null的值:①列写了 ...

  5. A Child's History of England.21

    There was one tall Norman Knight who rode before the Norman army on a prancing horse, throwing up hi ...

  6. CSS系列,清除浮动方法总结

    在非IE浏览器(如Firefox)下,当容器的高度为auto,且容器的内容中有浮动(float为left或right)的元素.在这种情况下,容器的高度不能自动伸长以适应内容的高度,使得内容溢出到容器外 ...

  7. Shell学习(八)——dd命令

    一.dd命令的解释 dd:用指定大小的块拷贝一个文件,并在拷贝的同时进行指定的转换. 注意:指定数字的地方若以下列字符结尾,则乘以相应的数字:b=512:c=1:k=1024:w=2 参数注释: 1. ...

  8. 如何设置eclipse下查看java源码

    windows--preferences--java--installed jres --选中jre6--点击右边的edit--选中jre6/lib/rt.jar --点击右边的 source att ...

  9. SVN终端演练(个人开发\多人开发)

    SVN终端演练(个人开发) ### 1. 命令格式 命令行格式: svn <subcommand> [options] [args]       svn 子命令 [选项] [参数]     ...

  10. 监控网站是否异常的shell脚本

    本节内容:shell脚本监控网站是否异常,如有异常就自动发邮件通知管理员. 脚本检测流程,如下:1,检查网站返回的http_code是否等于200,如不是200视为异常.2,检查网站的访问时间,超过M ...