LeetCode —— 单词接龙(Python)
使用字典,降低查找的复杂度。使用list会超时。
1 class Solution: 2 3 def nextWordsList(self, word, wordDict): 4 res_list = [] 5 for i in range(len(word)): 6 for j in string.ascii_lowercase: 7 new_word = list(word) 8 if j != word[i]: 9 new_word[i] = j 10 new_word = ''.join(new_word) 11 if new_word in wordDict: 12 res_list.append(new_word) 13 del wordDict[new_word] 14 return res_list 15 16 17 def bfs(self, beginWord, endWord, wordDict): 18 # 返回一个int 19 queue = [] 20 queue.append([beginWord, 1]) 21 while queue: 22 word, step = queue[0][0], queue[0][1] 23 queue.pop(0) 24 if word == endWord: return step 25 # 得到下一次变换一个单词,得到的单词列表 26 nextWords = self.nextWordsList(word, wordDict) 27 for j in nextWords: 28 queue.append([j, step+1]) 29 return 0 30 def ladderLength(self, beginWord, endWord, wordList): 31 """ 32 :type beginWord: str 33 :type endWord: str 34 :type wordList: List[str] 35 :rtype: int 36 """ 37 if beginWord in wordList: wordList.remove(beginWord) 38 wordDict = {} 39 for w in wordList: wordDict[w] = 1 40 return self.bfs(beginWord, endWord, wordDict)