标签:imp bsp ini ons rdd class type elf dict
思路:
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‘]))
标签:imp bsp ini ons rdd class type elf dict
原文地址:http://www.cnblogs.com/lettuan/p/6418027.html