美文网首页
81. LeetCode.127. 单词接龙

81. LeetCode.127. 单词接龙

作者: 月牙眼的楼下小黑 | 来源:发表于2019-03-04 22:58 被阅读4次
  • 标签: 广度遍历
  • 难度: 中等

  • 题目描述
  • 解法

beginWord 为根节点,逐层的构建树,每个子结点是父节点变化一个字符后,并且仍然在 wordlist 中的单词。 注意 wordlist 中用过的单词需要删除, 避免重复构建子结点.(为什么要避免? 反证法参考). 在逐层构造的过程中,若某个子结点是 endWord, 则返回其位置深度.

class Solution(object):
    def ladderLength(self, beginWord, endWord, wordList):
        """
        :type beginWord: str
        :type endWord: str
        :type wordList: List[str]
        :rtype: int
        """
        wordList.append(beginWord)
        fathers= [beginWord]
        children = []
        depth = 1
        n = len(beginWord)
        while fathers:
            for f in fathers:
                if f == endWord:
                    return depth
                for i in range(n):
                    for c in 'abcdefghijklmnopqrstuvwxyz':
                        child = f[:i] + c + f[i+1:]
                        if child in wordList:
                            wordList.remove(child)
                            children.append(child)
            depth += 1
            fathers = children
            children = []
            
        return 0
                    
  • 其他解法

暂略。

相关文章

  • 81. LeetCode.127. 单词接龙

    标签: 广度遍历 难度: 中等 题目描述 解法 以 beginWord 为根节点,逐层的构建树,每个子结点是父...

  • LeetCode-127-单词接龙

    LeetCode-127-单词接龙 127. 单词接龙[https://leetcode-cn.com/probl...

  • 单词接龙

    10.06 [codevs] 单词接龙题记 题目: 题目描述 Description 输入描述 Input Des...

  • 单词接龙

    题目 给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWo...

  • leetcode127 单词接龙

    题目 单词接龙 分析 分析同leetcode433 最小基因变化 代码

  • 127. 单词接龙

    127. 单词接龙[https://leetcode-cn.com/problems/word-ladder/] ...

  • 12 - Hard - 单词接龙

    定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的...

  • 127. 单词接龙

    题目描述 给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 end...

  • 127. 单词接龙

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

  • LeetCode - #127 单词接龙

    前言 我们社区陆续会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swi...

网友评论

      本文标题:81. LeetCode.127. 单词接龙

      本文链接:https://www.haomeiwen.com/subject/kmxguqtx.html