【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: 5Explanation: 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 0visited = set([beginWord])chrs = [chr(ord('a') + i) for i in range(26)]bfs = collections.deque([beginWord])res = 1while 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] = ctransword = "".join(originlist)if transword not in visited:if transword == endWord:return res + 1elif transword in wordset:bfs.append(transword)visited.add(transword)res += 1return 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 lengthfor 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)相关推荐
- 【重点BFS】LeetCode 127. Word Ladder
LeetCode 127. Word Ladder Solution1:我的超过40%的AC的答案 原先利用BFS做但是内存溢出未能AC:进过修改加上了标记是否访问过的visited数组,可以AC啦~ ...
- LeetCode 127. Word Ladder
原题链接在这里:https://leetcode.com/problems/word-ladder/ 题目: Given two words (beginWord and endWord), and ...
- [LeetCode#127]Word Ladder
---恢复内容开始--- The problem: Given two words (start and end), and a dictionary, find the length of shor ...
- 【难点+重点BFS】LeetCode 126. Word Ladder II
LeetCode 126. Word Ladder II Solution1: 参考自花花酱:http://zxi.mytechroad.com/blog/searching/leetcode-126 ...
- Leetcode的word ladder问题
127. Word Ladder 题意如下: 给定一个开始字符串和结束字符串以及含有大量字符串的字典,要求通过一定规则,能从开始字符串变换到结束字符串,求其最小变换字符串数目,该规则如下: 1 从开始 ...
- 【LeetCode】3Sum Closest 解题报告
[题目] Given an array S of n integers, find three integers in S such that the sum is closest to a give ...
- 【LeetCode】77. Combinations 解题报告(Python C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:递归 方法二:回溯法 日期 题目地址:htt ...
- Leetcode 1190. Reverse Substrings Between Each Pair of Parentheses解题报告(python)
1190. Reverse Substrings Between Each Pair of Parentheses Reverse Substrings Between Each Pair of Pa ...
- 【LeetCode】517. 超级洗衣机 解题报告 (python)
原题地址:https://leetcode-cn.com/problems/super-washing-machines/submissions/ 题目描述: 假设有 n 台超级洗衣机放在同一排上.开 ...
最新文章
- 2008年上半年 网络工程师 上下午试卷【附带答案】
- postgresql 使用指南
- Win 7 RC版即将发布 新功能提前爆料
- 高度平衡树 -- AVL 树
- 2020太湖杯 | Wp及复现
- 第一次学游泳技巧_游泳前,让自己不再怕水的5堂准备课
- 写给我们奔三的80后们……
- 【语音识别】基于matlab傅立叶变换0-9数字语音识别【含Matlab源码 384期】
- java word转pdf_Java中Word转PDF解决方案
- VB/VBA之死,何时休?
- 爱粤语软件:普通话和粤语转换
- 单片机---STM8开发环境搭建与标准库工程创建
- c语言求圆锥的表面积和体积_C语言-圆形体体积计算器,1:计算球体;2:计算圆柱体;3:计算圆锥体...
- 正交相机和透视相机的区别
- php批量下载图片并打包
- 招聘信息薪资范围是12-20K,能否要20K的薪资?
- 假设你有8个球,其中一个略微重一些,但是找出这个球的唯一方法是将两个球放在天平上对比。最少要称多少次才能找出这个较重的球?
- 明解C语言入门篇_第9章_字符串的基本知识
- 20145326蔡馨熤《信息安全系统设计基础》期末总结
- 小程序后台数据交互-个人中心
热门文章
- (续)SSM整合之springmvc笔记(@RequestMapping注解)(P124-130)
- 怎么查看linux服务器品牌,怎么查看Linux服务器硬件信息,这些命令告诉你
- 亚马逊定制VP Review是什么原理?
- 推荐:大文件查找,快速扫描,图像分析并清理硬盘垃圾文件的绝佳好工具!
- 西部光伏电站不景气 屋顶光伏春天将至
- alm系统的使用流程_Polarion ALM—涵盖您所需的一切于整体统一的 ALM 解决方案之中...
- java 支付宝回调返回值,支付宝APP支付Java回调具体步骤
- 2020大学生网络安全知识大赛总决赛模拟卷错题集(10)
- 为什么访问亚马逊的网站卡顿?
- c语言总统竞选问题,一上台就紧张?这个模型生成演讲替身,肢体语言比总统候选人还丰富...