標籤:ack width code type end return 技術 queue lis
使用字典,降低尋找的複雜度。使用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] = j10 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_list15 16 17 def bfs(self, beginWord, endWord, wordDict):18 # 返回一個int19 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 step25 # 得到下一次變換一個單詞,得到的單字清單26 nextWords = self.nextWordsList(word, wordDict)27 for j in nextWords:28 queue.append([j, step+1])29 return 030 def ladderLength(self, beginWord, endWord, wordList):31 """32 :type beginWord: str33 :type endWord: str34 :type wordList: List[str]35 :rtype: int36 """37 if beginWord in wordList: wordList.remove(beginWord)38 wordDict = {}39 for w in wordList: wordDict[w] = 140 return self.bfs(beginWord, endWord, wordDict)
LeetCode —— 單詞接龍(Python)