t********n 发帖数: 611 | 1 用的bfs, 总是得到TLE结果。请问还有什么办法可以更快?谢谢!
Python code :
class Solution:
# @param start, a string
# @param end, a string
# @param dict, a set of string
# @return an integer
def ladderLength(self, start, end, d):
d = set(d)
q = []
dis = {}
dis[start] = 1
q.append(start)
letters = string.letters[0:26]
while q !=[]:
x = q.pop()
# print x
for i in range(len(x)):
for l in letters:
xx = list(x)
xx[i] = l
newWord = ("").join(xx)
if newWord != x and newWord in d:
# print "newWord:", newWord
dis[newWord] = dis[x] + 1
q = [newWord] + q
if newWord == end:
return dis[newWord]
return 0 | t********n 发帖数: 611 | |
|