【python/leetcode/127】Word Ladder
阿新 • • 發佈:2018-11-03
題目
https://leetcode.com/problems/word-ladder
實現程式碼
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
import collections
if endWord not in wordList:
return 0
wordList = set(wordList)
queue = collections.deque([[beginWord, 1]])
while queue:
word, length = queue.popleft()
if word == endWord:
return length
for i in range(len(word) ):
for c in 'abcdefghijklmnopqrstuvwxyz':
next_word = word[:i] + c + word[i+1:]
if next_word in wordList:
wordList.remove(next_word)
queue.append([next_word, length + 1])
return 0
總結
用python寫這個題目,是比較tricky的,下次還是使用java寫吧(等我熟悉以後),效率太低了,很容易就超時了
Runtime: 532 ms, faster than 49.55% of Python online submissions for Word Ladder.
這是我的效率,漫如龜