[leetcode]Word Ladder II @ Python
[leetcode]Word Ladder II @ Python
原题地址:http://oj.leetcode.com/problems/word-ladder-ii/
参考文献:http://blog.csdn.net/doc_sgl/article/details/13341405
http://chaoren.is-programmer.com/
题意:给定start单词,end单词,以及一个dict字典。要求找出start到end的所有最短路径,路径上的每个单词都要出现在dict中,且每次改变一个字母。如start="hit"; end="cog"; dict={"hot","dot","dog","lot","log"},则答案为:[["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]。这是leetcode oj给的例子。我在实现的时候发现这个例子有点问题:end单词不在dict中。实际的测试用例应该是start和end单词都在dict中的,因为如果提前做一个删除start或者end单词的操作的话,就通不过了。我用正确的程序去测试oj给的这个例子也无法通过,就姑且认为start单词和end单词都在dict中吧,这样写出来的程序才能通过。
Word Ladder II这一道题还是比较难的,是leetcode oj中通过率最低的一道题。而由于我一直在用python来刷题,且一直在网上找不到用python写的解法,自己又写不出来,所以参考了网上的C++解法以及kitt的python程序,在此表示感谢。
解题关键点:1,这里的dict是python中的set()类型。
2,使用前驱单词表prevMap,是python中的字典类型。用来记录单词的前驱。比如prevMap={cog:[log, dog]}表示cog的前驱是:log和dog。
3,在word ladder这道题中我们使用了队列,在word ladder ii中也需要使用队列,只不过在这个程序中使用了两个set()来模拟队列。candidates[previous]中存储的是前面一层的单词。如{dot,lot}为第三层单词。在程序开始执行时,现将前面一层的单词即candidates[previous]中的单词在dict中删除,再将candidates[current]清空,然后根据candidates[previous]中的单词寻找下一层的单词,如{dot,lot}的下一层为{dog,log},并将{dog,log}存入candidates[current]中,同时将单词存入前驱单词表中。下一次循环开始时,上一次循环的candidates[current]变成了candidates[previous],而上一次循环的candidates[previous]变成了candidates[current]并清空。如此反复执行,当某一次循环中的candidates[current]中出现了end单词时,说明我们的路径已经找出来了,工作完成了。
4,程序中使用了一个子函数buildpath来重建每一条路径。如oj给的例子所产生的prevMap={cog:[log,dog], log:[lot], dog:[dot], dot:[hot], lot:[hot], hot:[hit]},这个prevMap可以使用DFS来重建每一条路径。
源代码:
class Solution:
# @param start, a string
# @param end, a string
# @param dict, a set of string
# @return a list of lists of string
def findLadders(self, start, end, dict):
def buildpath(path, word):
if len(prevMap[word])==0:
path.append(word); currPath=path[:]
currPath.reverse(); result.append(currPath)
path.pop();
return
path.append(word)
for iter in prevMap[word]:
buildpath(path, iter)
path.pop() result=[]
prevMap={}
length=len(start)
for i in dict:
prevMap[i]=[]
candidates=[set(),set()]; current=0; previous=1
candidates[current].add(start)
while True:
current, previous=previous, current
for i in candidates[previous]: dict.remove(i)
candidates[current].clear()
for word in candidates[previous]:
for i in range(length):
part1=word[:i]; part2=word[i+1:]
for j in 'abcdefghijklmnopqrstuvwxyz':
if word[i]!=j:
nextword=part1+j+part2
if nextword in dict:
prevMap[nextword].append(word)
candidates[current].add(nextword)
if len(candidates[current])==0: return result
if end in candidates[current]: break
buildpath([], end)
return result
[leetcode]Word Ladder II @ Python的更多相关文章
- LeetCode :Word Ladder II My Solution
Word Ladder II Total Accepted: 11755 Total Submissions: 102776My Submissions Given two words (start ...
- LeetCode: Word Ladder II 解题报告
Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation s ...
- [LeetCode] Word Ladder II 词语阶梯之二
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- LeetCode: Word Ladder II [127]
[题目] Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) ...
- [leetcode]Word Break II @ Python
原题地址:https://oj.leetcode.com/problems/word-break-ii/ 题意: Given a string s and a dictionary of words ...
- [LeetCode] Word Ladder II
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- leetcode—word ladder II
1.题目描述 Given two words (start and end), and a dictionary, find all shortest transformation sequence( ...
- LeetCode:Word Ladder I II
其他LeetCode题目欢迎访问:LeetCode结题报告索引 LeetCode:Word Ladder Given two words (start and end), and a dictiona ...
- [Leetcode Week5]Word Ladder II
Word Ladder II 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/word-ladder-ii/description/ Descripti ...
随机推荐
- 24.python中类的方法
类中的方法,其实就是类中的函数,可以分为:实例方法,类方法,静态方法.方法和字段一样,也是属于类的属性,所以也具有运行中修改的特效, 但一般不推荐这样做. 我在类的基本语法中,介绍了构造器方法:__i ...
- 51nod 1584加权约数和
学到了好多东西啊这题... https://blog.csdn.net/sdfzyhx/article/details/72968468 #include<bits/stdc++.h> u ...
- ZJOI2019day1退役记
ZJOI2019day1退役记 每天都在划水,考场上心态炸了,也没什么好说的. 有人催我更退役记,等成绩出来了再更更吧,成绩出来也没心情更了,落差好大,还打不过文化课选手 虽然被卡常数卡到心态爆炸,但 ...
- 吴恩达-coursera-机器学习-week10
十七.大规模机器学习(Large Scale Machine Learning) 17.1 大型数据集的学习 17.2 随机梯度下降法 17.3 小批量梯度下降 17.4 随机梯度下降收敛 17.5 ...
- 解决Android LogCat 输出乱码的问题(转)
Android日志系统提供了记录和查看系统调试信息的功能.日志都是从各种软件和一些系统的缓冲区中记录下来的. 可以使用adb的logcat 命令来查看系统日志缓冲区的内容,但是在实际操作时,会发现在C ...
- SGU 104. Little shop of flowers (DP)
104. Little shop of flowers time limit per test: 0.25 sec. memory limit per test: 4096 KB PROBLEM Yo ...
- OpenSSL开发学习总结
from https://mp.weixin.qq.com/s/sJBGJ88_-N-LdA8EHywfAA 1.对称加密算法 对称加密算法只使用一个密钥.数据的发送方准备好原始数据和一个加密密钥,加 ...
- Revit API修改保温层厚度
start [Transaction(TransactionMode.Manual)] [Regeneration(RegenerationOption.Manual)] ;, newLayer); ...
- [Winform]CefSharp ——js调用c#方法
摘要 有时我们在winform中嵌入浏览器,需要在页面上读取电脑上的一些信息,这个时候就需要用到CefSharp的RegisterJsObject进行注册方法然后供js进行调用了. 一个例子 我们在w ...
- 使用Axure RP原型设计实践03,制作一个登录界面的原型
本篇体验做一个登录界面的原型. 登录页 首先在Page Style里为页面设置背景色. 如果想在页面中加图片,就把Image部件拖入页面,并设置x和y轴.双击页面中的Image部件可以导入图片.在Im ...