题目
思路
在计算disOne的时候,有技巧。
如果遍历所有单词,时间复杂度
O(n∗L)
O
(
n
∗
L
)
,会超时
改成遍历所有字母,把单词存放到dict中,时间复杂度O(L)
代码
class Solution:
def disOne(self, word1, wordDict):
res_list = []
word = [i for i in word1]
for i in range(len(word)):
oriAlpha = word[i]
for w in string.ascii_lowercase:
word[i] = w
new_word = ''.join(word)
if new_word in wordDict:
del wordDict[new_word]
res_list.append(new_word)
word[i] = oriAlpha
return res_list
def bfs(self, beginWord, endWord, wordDict):
queue = []
queue.append([beginWord,1])
while queue:
word, step= queue[0][0], queue[0][1]
queue.pop(0)
if word == endWord: return step
wordList = self.disOne(word, wordDict)
for word in wordList:
queue.append([word, step + 1])
return 0
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
#if endWord not in wordList: wordList.append(endWord)
if beginWord in wordList:wordList.remove(beginWord)
wordDict = {}
for w in wordList: wordDict[w] = 1
return self.bfs(beginWord, endWord, wordDict)