Skip to content

Commit a54370d

Browse files
committed
Update the solution to Alien Dictionary
1 parent 7464e76 commit a54370d

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

Graph/AlienDictionary.swift

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ class AlienDictionary {
3838
}
3939

4040
private func initGraph(_ words: [String]) -> ([Character: Int], [Character: [Character]]) {
41-
var indegrees = [Character: Int](), charToChars = [Character: [Character]]()
41+
var indegrees = [Character: Int](), charToChars = [Character: [Character]
4242

4343
// init indegress and charToChars
4444
words.forEach { word in
@@ -51,15 +51,19 @@ class AlienDictionary {
5151
// refactor indegress and charToChars based on words
5252
for i in 0..<words.count - 1 {
5353
let currentWord = Array(words[i]), nextWord = Array(words[i + 1])
54-
var j = 0
5554

56-
while j < currentWord.count && j < nextWord.count {
55+
for j in 0..<min(currentWord.count, nextWord.count) {
5756
let currentChar = currentWord[j], nextChar = nextWord[j]
5857

5958
if nextChar == currentChar {
60-
j += 1
59+
60+
if j + 1 == right.count && right.count < left.count {
61+
return ([Character: Int](), [Character: [Character]]())
62+
}
63+
6164
continue
6265
}
66+
6367
if let toChars = charToChars[currentChar], toChars.contains(nextChar) {
6468
break
6569
}

0 commit comments

Comments
 (0)