【LeetCode】127. Word Ladder 解题报告(Python)
作者: 负雪明烛
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:
- Only one letter can be changed at a time.
- 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)的更多相关文章
- [LeetCode] 127. Word Ladder 单词阶梯
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...
- leetcode 127. Word Ladder、126. Word Ladder II
127. Word Ladder 这道题使用bfs来解决,每次将满足要求的变换单词加入队列中. wordSet用来记录当前词典中的单词,做一个单词变换生成一个新单词,都需要判断这个单词是否在词典中,不 ...
- Leetcode#127 Word Ladder
原题地址 BFS Word Ladder II的简化版(参见这篇文章) 由于只需要计算步数,所以简单许多. 代码: int ladderLength(string start, string end, ...
- LeetCode 127. Word Ladder 单词接龙(C++/Java)
题目: Given two words (beginWord and endWord), and a dictionary's word list, find the length of shorte ...
- leetcode@ [127] Word Ladder (BFS / Graph)
https://leetcode.com/problems/word-ladder/ Given two words (beginWord and endWord), and a dictionary ...
- Java for LeetCode 127 Word Ladder
Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformatio ...
- leetcode 127. Word Ladder ----- java
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...
- [leetcode]127. Word Ladder单词接龙
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...
- [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 ...
随机推荐
- Excel-条件判断
5.条件判断 IFS(条件1,真1,假1-条件2,真2,假2-条件n,真n,假n-条件n+1,...,TRUE,执行) #可以嵌套164个(大概!具体忘了) IF(条件1,真,假)
- 日常Java 2021/11/17
应用程序转换成Applet 将图形化的Java应用程序(是指,使用AWT的应用程序和使用java程序启动器启动的程序)转换成嵌入在web页面里的applet是很简单的.下面是将应用程序转换成.Appl ...
- Docker学习(五)——Docker仓库管理
Docker仓库管理 仓库(Repository)是集中存放镜像的地方. 1.Docker Hub 目前Docker官方维护了一个公共仓库Docker Hub.大部分需求都可以通过 ...
- centos 7 重新获取IP地址
1.安装软件包 dhclient # yum install dhclient 2.释放现有IP # dhclient -r 3.重新获取 # dhclient 4.查看获取到到IP # ip a
- Linux:sqlldr命令
第一步:写一个 ctl格式的控制文件 CTL 控制文件的内容 : load data --1. 控制文件标识 infile 'xxx.txt' --2. 要导入的数据文件名 insert into t ...
- Spring Cloud中使用Eureka
一.创建00-eurekaserver-8000 (1)创建工程 创建一个Spring Initializr工程,命名为00-eurekaserver-8000,仅导入Eureka Server依赖即 ...
- SpringBoot中使用JUnit4(入门篇)
添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>sp ...
- 通过 Ajax 发送 PUT、DELETE 请求的两种实现方式
一.普通请求方法发送 PUT 请求 1. 如果不用 ajax 发送 PUT,我们可以通过设置一个隐藏域设置 _method 的值,如下: <form action="/emps&quo ...
- Jenkins优化
目录 一.修改 JVM 的内存配置 二.修改jenkins 主目录 一.修改 JVM 的内存配置 Jenkins 启动方式有两种方式,一种是以 Jdk Jar 方式运行,一种是将 War 包放在 To ...
- Python openpyxl的使用
import openpyxl from openpyxl.styles import Font, colors, Alignment wb = openpyxl.load_workbook('C:\ ...