1. 程式人生 > >LeetCode —— 單詞接龍(Python)

LeetCode —— 單詞接龍(Python)

style leetcode 圖片 back pop str 超時 type return

技術分享圖片

技術分享圖片

使用字典,降低查找的復雜度。使用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)

LeetCode —— 單詞接龍(Python)