设为首页 收藏本站
查看: 504|回复: 0

[经验分享] [python leetcode] Word Ladder II (very hard)[非常难,放弃]

[复制链接]

尚未签到

发表于 2015-11-30 10:14:10 | 显示全部楼层 |阅读模式
  Word Ladder II
  描述
  Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start
  to end, such that:
  · Only one letter can be changed at a time
  · Each intermediate word must exist in the dictionary
  For example, Given:
  start = "hit"
  end = "cog"
  dict = ["hot","dot","dog","lot","log"]
  Return
  [
  ["hit","hot","dot","dog","cog"],
  ["hit","hot","lot","log","cog"]
  ]
  Note:
  · All words have the same length.
  · All words contain only lowercase alphabetic characters.
  题意:给定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(是字典类型)来记录单词的前驱。比如prevMap={cog:[log, dog]}表示cog的前驱是:log和dog。
  3,在word ladder这道题中我们使用了队列,在word ladder ii中也需要使用队列,只不过在这个程序中使用了两个set()来模拟队列(candidates)。candidates[previous]中存储的是前一层的单词。如{dot,lot}为第3层单词。在程序开始执行时,先将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’], ‘lot’:[‘hot’],’dot’:[‘hot’], ‘hot’:[‘hit’]},这个prevMap可以使用DFS来重建每一条路径。
  本解法来自:
  http://www.cnblogs.com/zuoyuan/p/3697045.html
  但是很多细节不明白,寻求大家的帮助.
  



1 class Solution:
2     # @param start, a string
3     # @param end, a string
4     # @param dict, a set of string
5     # @return a list of lists of string
6     def findLadders(self, start, end, dict):
7         def buildpath(path, word): # path is a list; word is a string
8             if len(prevMap[word])==0: #prevMap: dict  #Blank prevMap means all the node in the path is visited
9                 path.append(word);
10                 currPath=path[:]   # hard copy path to currPath. No link between pat and currPath
11                 currPath.reverse();
12                 result.append(currPath)
13                 path.pop(); #remove the end element
14                 return
15             path.append(word)
16             for iter in prevMap[word]: # reverse the path,
17                 buildpath(path, iter)
18             path.pop()
19         
20         result=[]
21         prevMap={} # prevMap is a dict
22         length=len(start)
23         for i in dict: #dict: is a set
24             prevMap=[] # set the value for each key as blank string
25         candidates=[set(),set()]; current=0; previous=1
26         candidates[current].add(start) # set0 add start
27         while True:
28             current, previous=previous, current           #下一次循环开始时,上一次循环的candidates[current]变成了candidates[previous],而上一次循环的candidates[previous]变成了candidates[current]并清空
29             for i in candidates[previous]: dict.remove(i) #先将candidates[previous]中的单词(前一层的单词)在dict中删除
30             candidates[current].clear()                   #再将candidates[current]清空
31             for word in candidates[previous]:             #再据candidates[previous]中的单词寻找下一层的单词
32                 for i in range(length):
33                     part1=word[:i]; part2=word[i+1:]
34                     for j in 'abcdefghijklmnopqrstuvwxyz':
35                         if word!=j:
36                             nextword=part1+j+part2
37                             if nextword in dict:
38                                 candidates[current].add(nextword) #将下一层存入candidates[current]中
39                                 prevMap[nextword].append(word)    #同时将单词存入前驱单词表中
40             if len(candidates[current])==0: return result         #当集合为空,返回结果
41             if end in candidates[current]: break #当循环中的candidates[current]中出现了end单词时,说明我们的路径已经找出来了,工作完成了。
42         buildpath([], end) #重建每一条路径。prevMap is a dict,这个prevMap可以使用DFS来重建每一条路径。
43         return result
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-145256-1-1.html 上篇帖子: Appium环境搭建python篇(mac系统) 下篇帖子: Python学习之:pycharm配置
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表