Leetcode 127. Word Ladder
Posted lettuan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 127. Word Ladder相关的知识,希望对你有一定的参考价值。
思路:
1 class Solution(object): 2 def __init__(self): 3 return 4 5 def ladderLength(self, beginWord, endWord, wordList): 6 """ 7 :type beginWord: str 8 :type endWord: str 9 :type wordList: List[str] 10 :rtype: int 11 """ 12 from collections import defaultdict, deque 13 queue = deque([[beginWord, 1]]) 14 visited = set([beginWord]) 15 neighbors = defaultdict(list) 16 for word in wordList: 17 for x in range(len(word)): 18 token = word[:x] + ‘_‘ + word[x + 1:] 19 neighbors[token] += word, 20 while queue: 21 word, length = queue.popleft() 22 if self.wordDist(word, endWord) <= 1: 23 return length + 1 24 for x in range(len(word)): 25 token = word[:x] + ‘_‘ + word[x + 1:] 26 for ladder in neighbors[token]: 27 if ladder not in visited: 28 visited.add(ladder) 29 queue += [ladder, length + 1], 30 return 0 31 32 def wordDist(self, wordA, wordB): 33 return sum([wordA[x] != wordB[x] for x in range(len(wordA))]) 34 35 SL = Solution() 36 print(SL.ladderLength(‘hit‘, ‘cog‘, [‘hot‘, ‘dot‘, ‘dog‘, ‘lot‘, ‘log‘]))
以上是关于Leetcode 127. Word Ladder的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 127. Word Ladder ----- java
(Java) LeetCode 127. Word Ladder —— 单词接龙
LeetCode Top Interview Questions 127. Word Ladder (Java版; Medium)