BFS——单词接龙,这种题一定要当心环路

120. 单词接龙

中文
English

给出两个单词(startend)和一个字典,找出从startend的最短转换序列,输出最短序列的长度。

变换规则如下:

  1. 每次只能改变一个字母。
  2. 变换过程中的中间单词必须在字典中出现。(起始单词和结束单词不需要出现在字典中)

样例

样例 1:

输入:start = "a",end = "c",dict =["a","b","c"]
输出:2
解释:
"a"->"c"

样例 2:

输入:start ="hit",end = "cog",dict =["hot","dot","dog","lot","log"]
输出:5
解释:
"hit"->"hot"->"dot"->"dog"->"cog"

注意事项

  • 如果不存在这样的转换序列,返回 0。
  • 所有单词具有相同的长度。
  • 所有单词只由小写字母组成。
  • 字典中不存在重复的单词。
  • 你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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):
        # write your code here
        if len(start) != len(end):
            return False
             
        if not dict:
            return False
             
        dict.add(end)
        seen = set()
         
        def get_trans_words(w):
            ans = []
            for i in range(len(w)+1):
                for c in 'abcdefghijklmnopqrstuvwxyz':
                    new_word = w[:i]+c+w[i+1:]
                    if new_word in dict:
                        if new_word not in seen:
                            seen.add(new_word)
                            ans.append(new_word)
             
            return ans
         
        """
        def has1char_diff(w1, w2):
            cnt = 0
            for i,c in enumerate(w1):
                if c != w2[i]:
                    cnt += 1
                     
            return cnt == 1
        """
         
        q = get_trans_words(start)
        ans = 1
        while q:
            q2 = []
            for w in q:
                if w == end: #has1char_diff(w, end):
                    return ans+1
                q2.extend(get_trans_words(w))
            q = q2
            ans += 1
             
        return 0

 

posted @   bonelee  阅读(180)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
历史上的今天:
2017-01-13 YCSB benchmark测试cassandra性能——和web服务器测试性能结果类似
2017-01-13 使用cqlsh远程连接cassandra——设置cassandra.yaml里rpc_address和listen_address为ipv4地址即可
2017-01-13 MongoDB架构——记得结合前面的文章看,里面的图画的很好
2017-01-13 ycsb两个阶段说明
2017-01-13 YCSB benchmark测试mongodb性能——和web服务器测试性能结果类似
2017-01-13 MongoDB GridFS——本质上是将一个文件分割为大小为256KB的chunks 每个chunk里会放md5标识 取文件的时候会将这些chunks合并为一个整体返回
2017-01-13 mongodb分片介绍—— 基于范围(数值型)的分片 或者 基于哈希的分片
点击右上角即可分享
微信分享提示