zoukankan      html  css  js  c++  java
  • leetcode @python 127. Word Ladder

    题目链接

    https://leetcode.com/problems/word-ladder/

    题目原文

    Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:

    Only one letter can be changed at a time
    Each intermediate word must exist in the word list
    For example,

    Given:
    beginWord = "hit"
    endWord = "cog"
    wordList = ["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.

    题目大意

    给出开始单词、结束单词以及一个词典,求出从开始单词变换到结束单词所需要经过的词数,每次变换只能改变一个字母(若找不到这样的变化,返回0)

    解题思路

    根据开始单词,变换其中任意一个位置的字母,看新生成的单词是否在字典中出现,若新生成的单词等于结束单词,则结束,否则,继续变换新生成的单词

    代码

    class Solution(object):
        def ladderLength(self, beginWord, endWord, wordList):
            """
            :type beginWord: str
            :type endWord: str
            :type wordList: Set[str]
            :rtype: int
            """
            length = 2
            words = set([beginWord])
            wordList.discard(beginWord)
            wordList.discard(endWord)
    
            while words:
                newwords = set()
                for word in words:
                    for i in range(len(word)):
                        for c in "abcdefghijklmnopqrstuvwxyz":
                            new_word = word[:i] + c + word[i + 1:]
                            if new_word == endWord:
                                return length
                            if new_word in wordList:
                                newwords.add(new_word)
                words = newwords
                length += 1
                wordList -= words
            return 0
    
  • 相关阅读:
    POJ1251 Jungle Roads 【最小生成树Prim】
    聪明的kk
    日积月累:weightSum和layout_weight属性合用
    ubuntu 下舒畅的使用libreoffice
    maple 教程
    龙、虎、鲸书杂谈
    百度没出新算法之前这样的最好的的优化方案
    DWR入门实例(二)
    Android应用公布的准备——生成渠道包
    leetcode第一刷_Spiral Matrix II
  • 原文地址:https://www.cnblogs.com/slurm/p/5349422.html
Copyright © 2011-2022 走看看