LeetCode —— 單詞接龍(Python)

來源:互聯網
上載者:User

標籤: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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.