File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ from typing import (
2+ List ,
3+ )
4+
5+ import heapq
6+ heap = [c for c in indegree if indegree [c ] == 0 ]
7+ heapq .heapify (heap )
8+ res = []
9+
10+
11+ class Solution :
12+ """
13+ @param words: a list of words
14+ @return: a string which is correct order
15+ """
16+ def alien_order (self , words : List [str ]) -> str :
17+ # Write your code here
18+ adj = {c : set () for word in words for c in word }
19+ indegree = {c : 0 for c in adj }
20+
21+ for i in range (len (words ) - 1 ):
22+ w1 , w2 = words [i ], words [i + 1 ]
23+ minlen = min (len (w1 ), len (w2 ))
24+ if len (w1 ) > len (w2 ) and w1 [:minlen ] == w2 [:minlen ]:
25+ return ""
26+ for j in range (minlen ):
27+ if w1 [j ] != w2 [j ]:
28+ if w2 [j ] not in adj [w1 [j ]]:
29+ adj [w1 [j ]].add (w2 [j ])
30+ indegree [w2 [j ]] += 1
31+ break
32+
33+ while heap :
34+ c = heapq .heappop (heap )
35+ res .append (c )
36+ for nei in adj [c ]:
37+ indegree [nei ] -= 1
38+ if indegree [nei ] == 0 :
39+ heapq .heappush (heap , nei )
40+
41+ if len (res ) != len (adj ):
42+ return ""
43+
44+ return "" .join (res )
You can’t perform that action at this time.
0 commit comments