File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
1
+ import collections
2
+ class Solution :
3
+ def alien_order (self , words ):
4
+ graph = collections .defaultdict (set )
5
+ indegree = {}
6
+ for word in words :
7
+ for c in word :
8
+ indegree [c ] = 0
9
+ for i in range (len (words ) - 1 ):
10
+ w1 , w2 = words [i ], words [i + 1 ]
11
+ min_len = min (len (w1 ), len (w2 ))
12
+ if len (w1 ) > len (w2 ) and w1 [:min_len ] == w2 [:min_len ]:
13
+ return ""
14
+ for j in range (min_len ):
15
+ if w1 [j ] != w2 [j ]:
16
+ if w2 [j ] not in graph [w1 [j ]]:
17
+ graph [w1 [j ]].add (w2 [j ])
18
+ indegree [w2 [j ]] += 1
19
+ break
20
+ queue = collections .deque ([c for c in indegree if indegree [c ] == 0 ])
21
+ res = []
22
+ while queue :
23
+ c = queue .popleft ()
24
+ res .append (c )
25
+ for nei in graph [c ]:
26
+ indegree [nei ] -= 1
27
+ if indegree [nei ] == 0 :
28
+ queue .append (nei )
29
+ return "" .join (res ) if len (res ) == len (indegree ) else ""
You can’t perform that action at this time.
0 commit comments