Skip to content

Commit 944bf05

Browse files
Solve : Alien Dictionary
1 parent 8161034 commit 944bf05

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

alien-dictionary/printjin-gmailcom.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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 ""

0 commit comments

Comments
 (0)