127. Word Ladder Leetcode Python

来源:互联网 发布:淘宝直通车有必要开吗 编辑:程序博客网 时间:2024/05/16 13:59
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence 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"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.


Note:
Return 0 if there is no such transformation sequence.
All words have the same length.

All words contain only lowercase alphabetic characters.


这题是用的breadth first search 把每个字母当成一个edge 用一个que 把每次得到的新的edge加进来 在dict里面把已经遍历过的节点删除了。

每过一个新的单词的复杂度为L×26 L 是单词的长度

代码如下:

class Solution:    # @param start, a string    # @param end, a string    # @param dict, a set of string    # @return an integer    def ladderLength(self, start, end, dict):        dict.add(end)        q=[]        q.append((start,1))        while q:            curr=q.pop(0)            curword=curr[0]            curlen=curr[1]            if curword==end:                return curlen            for i in range(len(curword)):                part1=curword[:i]                part2=curword[i+1:]                for j in 'qwertyuiopasdfghjklzxcvbnm':                    if curword[i]!=j:                        nextword=part1+j+part2                        if nextword in dict:                            q.append((nextword,curlen+1))                            dict.remove(nextword)        return 0



0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 买家说我运费险没赔要投诉我怎么办 包邮有运费险的东西想退货怎么办 高锰酸钾沾到龟头上形成黑点怎么办 淘宝发货包邮买家退款运费怎么办 京东实名认证的手机号不用了怎么办 淘宝退货在自提柜 卖家不取怎么办 如果买家退货那卖家送的东西怎么办 陆金所注册手机号被占用要怎么办 重新登录而忘记密码和验证码怎么办 手机清理垃圾清掉的照片怎么办 收件人名字写错了拿不到快递怎么办 档案回原籍收件人写错了怎么办 寄申通快递收件人电话写错了怎么办 第三方支付倒闭了用户的钱怎么办啊 京东配送日期内货没送到家怎么办 拼多多拼单不成功优惠券退吗怎么办 退货退错了不发回来怎么办 商家总是不发退货地址过来怎么办 美团外卖下单后电话没改怎么办 从日本邮寄东西到中国被扣怎么办 淘宝拒收卖家收到货不退款怎么办 拒收的快递丢了卖家拒绝退款怎么办 京东买了东西超过七天想退货怎么办 微信买东西支付宝付款被骗怎么办 京东购物己付款卖家没发货怎么办 天猫先行退款卖家拒收怎么办 京东金条提前还款借不了怎么办 网银密码输入六次错误怎么办 迷失在时间和空间的交界处该怎么办 用卫生巾过后瘙痒起疹子了怎么办 装修公司倒闭了装修保修卡怎么办 丈夫把妻子的车抵押出去了怎么办 亚马逊海外购超过两万的额度怎么办 增值税申报表进项税转出忘填怎么办 一般纳税人注册下来后未营业怎么办 增值税税率把3错开成了5怎么办 在义乌做压痕加工老板拖欠钱怎么办 蓝洞棋牌是赌博输了几万怎么办 夏季来月经用卫生巾外阴瘙痒怎么办 用洗衣机洗衣服忘掏卫生纸了怎么办 剖腹产后一个月了还有血怎么办