作者: 负雪明烛
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:

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

Example 2:

Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"] 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是其实字符串的长度。

class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
wordset = set(wordList)
if endWord not in wordset:
return 0
visited = set([beginWord])
chrs = [chr(ord('a') + i) for i in range(26)]
bfs = collections.deque([beginWord])
res = 1
while bfs:
len_bfs = len(bfs)
for _ in range(len_bfs):
origin = bfs.popleft()
for i in range(len(origin)):
originlist = list(origin)
for c in chrs:
originlist[i] = c
transword = "".join(originlist)
if transword not in visited:
if transword == endWord:
return res + 1
elif transword in wordset:
bfs.append(transword)
visited.add(transword)
res += 1
return 0

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

class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
wordset = set(wordList)
bfs = collections.deque()
bfs.append((beginWord, 1))
while bfs:
word, length = bfs.popleft()
if word == endWord:
return length
for i in range(len(word)):
for c in "abcdefghijklmnopqrstuvwxyz":
newWord = word[:i] + c + word[i + 1:]
if newWord in wordset and newWord != word:
wordset.remove(newWord)
bfs.append((newWord, length + 1))
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. A Child's History of England.16

    CHAPTER 5 ENGLAND UNDER CANUTE THE DANE Canute reigned eighteen years. He was a merciless King at fi ...

  2. A Child's History of England.36

    CHAPTER 11 ENGLAND UNDER MATILDA AND STEPHEN The King was no sooner dead than all the plans and sche ...

  3. 零基础学习java------20---------反射

    1. 反射和动态代理 参考博文:https://blog.csdn.net/sinat_38259539/article/details/71799078 1.0 什么是Class: 我们都知道,对象 ...

  4. Stream collect Collectors 常用详细实例

    返回List集合: toList() 用于将元素累积到List集合中.它将创建一个新List集合(不会更改当前集合). List<Integer> integers = Arrays.as ...

  5. 【分布式】Zookeeper的Leader选举-选举过程介绍(经典的Paxos算法解析)

    一.前言 前面学习了Zookeeper服务端的相关细节,其中对于集群启动而言,很重要的一部分就是Leader选举,接着就开始深入学习Leader选举. 二.Leader选举 2.1 Leader选举概 ...

  6. D3基础入门四-事件处理

    6.5.0版 .on("mouseover", function(e,d) e: {"isTrusted":true} 第二个参考才是数据,但这在不同的环境可能 ...

  7. 【Services】【Web】【tomcat】配置tomcat支持https传输

    1. 基础: 1.1. 描述:内网的tomcat接到外网nginx转发过来的请求之后需要和外网的客户端进行通讯,为了保证通讯内容的安装,使用tomcat使用https协议. 1.2. 链接:http: ...

  8. Docker的常用命令总结

    一.普通指令 启动 Docker sudo systemctl start docker 停止 Docker sudo systemctl stop docker 普通重启 Docker sudo s ...

  9. 解决在进行socket通信时,一端输出流OutputStream不关闭,另一端输入流就接收不到数据

    输出的数据需要达到一定的量才会向另一端输出,所以在传输数据的末端添加 \r\n 可以保证不管数据量是多少,都立刻传输到另一端.

  10. 1.Thmeleaf模板引擎

    1.Thmeleaf的基本语法 大部分的Thmeleaf表达式都直接被设置到HTML节点中,作为HTML节点的一个属性存在,这样同一个模板文件既可以使用浏览器直接打开,也可以放到服务器中用来显示数据, ...