zoukankan      html  css  js  c++  java
  • 120. 单词接龙 (BFS)

    描述

    给出两个单词(start和end)和一个字典,找到从start到end的最短转换序列

    比如:

    每次只能改变一个字母。
    变换过程中的中间单词必须在字典中出现。
    如果没有转换序列则返回0。
    所有单词具有相同的长度。
    所有单词都只包含小写字母。

    样例

    给出数据如下:

    start = "hit"

    end = "cog"

    dict = ["hot","dot","dog","lot","log"]

    一个最短的变换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog",

    返回它的长度 5

    import collections
    
    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
            dict.add(end)
            wordLen = len(start)
            queue = collections.deque([(start, 1)])
            while queue:
                curr = queue.popleft()
                currWord = curr[0]; currLen = curr[1]
                if currWord == end: return currLen
                for i in range(wordLen):
                    part1 = currWord[:i]; part2 = currWord[i+1:]
                    for j in 'abcdefghijklmnopqrstuvwxyz':
                        if currWord[i] != j:
                            nextWord = part1 + j + part2
                            if nextWord in dict:
                                queue.append((nextWord, currLen + 1))
                                dict.remove(nextWord)
            return 0
    
  • 相关阅读:
    MySQL技术内幕 InnoDB存储引擎 之 InnoDB体系架构
    ORACLE同义词使用
    五大好用的开源MySQL管理工具推荐
    MySQL Online DDL工具
    10046事件及其用法介绍
    MySQL表碎片清理
    MyRocks安装部署
    TiDB单机安装测试
    TiDB官方文档
    GoldenGate—AUTORESTART配置
  • 原文地址:https://www.cnblogs.com/narjaja/p/9811007.html
Copyright © 2011-2022 走看看