forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
AlienDictionary.swift
87 lines (72 loc) · 2.36 KB
/
AlienDictionary.swift
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* Question Link: https://leetcode.com/problems/alien-dictionary/
* Primary idea: Topological sort, keep each character for a inDegree number and
* to characters list, use a queue to decrease inDegree and form the result
*
* Time Complexity: O(nm), Space Complexity: O(m),
* n represents words number, m represents length of a word
*/
class AlienDictionary {
var inDegrees = [Character: Int]()
var toWords = [Character: [Character]]()
var valid = true
func alienOrder(_ words: [String]) -> String {
var res = "", qChars = [Character]()
guard words.count > 0 else {
return res
}
initGraph(words)
for char in inDegrees.keys {
if inDegrees[char] == 0 {
qChars.append(char)
}
}
while !qChars.isEmpty {
let char = qChars.removeFirst()
res += String(char)
guard let toChars = toWords[char] else {
continue
}
for c in toChars {
inDegrees[c]! -= 1
if inDegrees[c] == 0 {
qChars.append(c)
}
}
}
return res.characters.count == inDegrees.count && valid ? res : ""
}
private func initGraph(_ words: [String]) {
for word in words {
for char in word.characters {
inDegrees[char] = 0
}
}
for i in 0 ..< words.count - 1 {
let prev = Array(words[i].characters)
let post = Array(words[i + 1].characters)
var j = 0
while j < prev.count && j < post.count {
if prev[j] == post[j] {
j += 1
} else {
addEdge(prev[j], post[j])
break
}
}
if prev.count != post.count && j == post.count {
valid = false
}
}
}
private func addEdge(_ from: Character, _ to: Character) {
if let inDegree = inDegrees[to] {
inDegrees[to] = inDegree + 1
}
if toWords[from] != nil {
toWords[from]!.append(to)
} else {
toWords[from] = [to]
}
}
}