作者: 负雪明烛
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. CPU大小端模式及转换

    通信协议中的数据传输.数组的存储方式.数据的强制转换等这些都会牵涉到大小端问题. CPU的大端和小端模式很多地方都会用到,但还是有许多朋友不知道,今天暂且普及一下. 一.为什么会有大小端模式之分呢? ...

  2. 小程序https启用tls1.2

    公司的web服务器是iis7,在开发微信小程序的时候,需要启用TLS1.2. 将下面的代码复制到文本,存为reg文档,双击搞定. Windows Registry Editor Version 5.0 ...

  3. adjust, administer

    adjust to just, exact. In measurement technology and metrology [度量衡学], calibration [校准] is the compa ...

  4. 虚拟机中安装centos系统的详细过程

    linux-centos的安装 检查电脑是否开启虚拟化,只有开启虚拟化才能安装虚拟机 新建虚拟机 鼠标点进去,选中红框所示,回车 登录: 输入默认用户名(超级管理员 root) 密码:安装时设置的密码

  5. [转]C++中const的使用

    原文链接:http://www.cnblogs.com/xudong-bupt/p/3509567.html 平时在写C++代码的时候不怎么注重const的使用,长久以来就把const的用法忘记了 写 ...

  6. 3.6 String 与 切片&str的区别

    The rust String  is a growable, mutable, owned, UTF-8 encoded string type. &str ,切片,是按UTF-8编码对St ...

  7. Linux学习 - IP地址配置

    1 首先选择桥接模式 2 配置IP.子网掩码.网关.DNS setup 本例中使用的是无线网连接, IP地址:  192.168.3.195 子网掩码:  255.255.255.0 网关: 192. ...

  8. 【Python】【Basic】【数据类型】基本数据类型

    1.数字 int(整型) 在32位机器上,整数的位数为32位,取值范围为-2**31-2**31-1,即-2147483648-2147483647 在64位系统上,整数的位数为64位,取值范围为-2 ...

  9. CentOS Linux下编译安装MySQL

    本文参考张宴的Nginx 0.8.x + PHP 5.2.13(FastCGI)搭建胜过Apache十倍的Web服务器(第6版)[原创]完成.所有操作命令都在CentOS 6.4 64位操作系统下实践 ...

  10. Oracle删除重复数据记录

    删除重复记录,利用ROWID 和MIN(或MAX)函数, ROWID在整个数据库中是唯一的,由Oracle自己产生和维护,并唯一标识一行(无论该表中是否有主键和唯一性约束),ROWID确定了每条记录在 ...