首页 > 代码库 > Leetcode 127. Word Ladder
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。