forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0269-alien-dictionary.py
37 lines (29 loc) · 1.02 KB
/
0269-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
classSolution:
defalienOrder(self, words: List[str]) ->str:
adj= {char: set() forwordinwordsforcharinword}
foriinrange(len(words) -1):
w1, w2=words[i], words[i+1]
minLen=min(len(w1), len(w2))
iflen(w1) >len(w2) andw1[:minLen] ==w2[:minLen]:
return""
forjinrange(minLen):
ifw1[j] !=w2[j]:
print(w1[j], w2[j])
adj[w1[j]].add(w2[j])
break
visited= {} # {char: bool} False visited, True current path
res= []
defdfs(char):
ifcharinvisited:
returnvisited[char]
visited[char] =True
forneighCharinadj[char]:
ifdfs(neighChar):
returnTrue
visited[char] =False
res.append(char)
forcharinadj:
ifdfs(char):
return""
res.reverse()
return"".join(res)