题目
思路
在判断字符距离的时候有坑。
假设单词长度为
L
L
,单词个数为
如果对于每一个单词,遍历list中所有单词,计算距离,时间复杂度为
O(n∗L)
O
(
n
∗
L
)
,在LintCode会超时。
对于每一个单词,遍历每一位的所有26个字母,组成新单词,再判断是否在词表中。词表处理成dict,这样时间复杂度为
O(L∗L)
O
(
L
∗
L
)
,AC。
代码
import string
class Solution:
"""
@param: start: a string
@param: end: a string
@param: dict: a set of string
@return: An integer
"""
def distanceOne(self, word, word_dict):
res_list = []
word = list(word)
for i, v in enumerate(word):
for c in string.ascii_lowercase:
if c != v:
word[i] = c
str_word = ''.join(word)
if str_word in word_dict and word_dict[str_word]:
res_list.append(str_word)
word[i] = v
return res_list
def bfs(self, start, end, word_list, word_dict):
count = 0
queue = []
queue.append([start, 1])
while queue:
word = queue[0][0]
distance = queue[0][1]
queue.pop(0)
if word == end:
return distance
for w in self.distanceOne(word, word_dict):
queue.append([w, distance + 1])
word_list.remove(w)
word_dict[w] = 0
return 0
def ladderLength(self, start, end, dict):
# write your code here
word_list = list(dict)
word_dict = {}
if end not in word_list:
word_list.append(end)
for word in word_list:
word_dict[word] = 1
return self.bfs(start, end, word_list, word_dict)