版权声明:小明酱私有,私自转载要捶你小胸口哦~ https://blog.csdn.net/alicelmx/article/details/83310523
题目
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.
这是我的效率,漫如龟