zoukankan      html  css  js  c++  java
  • 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 是非空的,且二者不相同。
    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
    
  • 相关阅读:
    mysql 数据库引擎
    dubbo 微服务
    spring 属性文件加载接口---PropertySourceLoader
    Shiro架构
    HTTP状态码
    Shiro 修改权限,刷新权限
    Consul 架构(译)
    Java EE平台介绍(译)
    Java SPI机制
    Otb_000_ElementUI 的 Drawer组件无法上下滚动没有滚动条
  • 原文地址:https://www.cnblogs.com/bonelee/p/14275087.html
Copyright © 2011-2022 走看看