-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path01_alien_dictionary.py
63 lines (43 loc) · 1.54 KB
/
01_alien_dictionary.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Solution:
def alien_order(self, words: list[str]) -> str:
adj = { char:set() for w in words for char in w }
for i in range(len(words) - 1):
w1, w2 = words[i], words[i + 1]
minLen = min(len(w1), len(w2))
if len(w1) > len(w2) and w1[:minLen] == w2[:minLen]:
return ""
for j in range(minLen):
if w1[j] != w2[j]:
adj[w1[j]].add(w2[j])
break
visit = {} # False = it is visited, True = it is in the current path
res = []
def dfs(char):
if char in visit:
return visit[char]
visit[char] = True
for nei in adj[char]:
if dfs(nei):
return True
visit[char] = False
res.append(char)
# for char in adj:
# if dfs(char):
# return ""
for char in sorted([c for c in adj.keys()], reverse=True):
if dfs(char):
return ""
res.reverse()
return "".join(res)
if __name__ == "__main__":
obj = Solution()
words1 = ["wrt","wrf","er","ett","rftt"]
print(obj.alien_order(words = words1))
words2 = ["z","x"]
print(obj.alien_order(words = words2))
words3 = ["z","o"]
print(obj.alien_order(words = words3))
words4 = ["hrn","hrf","er","enn","rfnn"]
print(obj.alien_order(words = words4))
word5 = ["ab","adc"]
print(obj.alien_order(words = word5))