我正在解决这个LeetCode问题,这是我的代码:
class Solution:
def alienOrder(self, words: List[str]) -> str:
adjacent = defaultdict(set)
for i in range(1, len(words)):
w1, w2 = words[i - 1], words[i]
min_len = min(len(w1), len(w2))
if len(w1) > len(w2) and w1[:min_len] == w2[:min_len]:
return ""
for j in range(min_len):
if w1[j] != w2[j]:
adjacent[w1[j]].add(w2[j]) # modify, not in the loop causing error
break
visited = dict()
res = []
def dfs(c):
if c in visited:
return visited[c]
visited[c] = True
for neighbor in adjacent[c]: # read only
if dfs(neighbor):
return True
visited[c] = False
res.append(c)
return False
for c in adjacent: # RuntimeError: dictionary changed size during iteration
if dfs(c):
return ''
return ''.join(reversed(res))
这行代码 for c in adjacent
报错 "RuntimeError: dictionary changed size during iteration",我不太理解。在 dfs()
中我没有修改 adjacent
,对吗?
adjacent
本身的键c
检查adjacent[c]
。这会导致什么错误? - johandfs(neighbor)
时,neighbor
可能不在字典中。第一次调用 dfs,dfs(c)
,完全没有问题。 - johan