Alien Dictionary(topo)
Last updated
Last updated
import collections
import heapq
class Solution:
"""
@param words: a list of words
@return: a string which is correct order
"""
def alienOrder(self, words):
# Write your code here
#不初始化的话会忽略头结点
indegree = {j:0 for w in words for j in w}
graph = {j:[] for w in words for j in w}
n = len(words)
for i in range(n-1):
for j in range(min(len(words[i]),len(words[i+1]))):
if words[i][j] != words[i+1][j]:
graph[words[i][j]].append(words[i+1][j])
indegree[words[i+1][j]] += 1
break #每次只相邻2个word比较,所以要Break
q = [k for k,v in indegree.items() if v == 0]
heapq.heapify(q)#保持最小字典序,必须heapify
ret = ""
while q:
cur = heapq.heappop(q)
ret += cur
for i in graph[cur]:
indegree[i]-=1
if not indegree[i]:
heapq.heappush(q,i)
if len(ret) != len(indegree):
return ""
return ret