forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Array] Add a solution to Verifying an Alien Dictionary
- Loading branch information
Showing
2 changed files
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
/** | ||
* Question Link: https://leetcode.com/problems/verifying-an-alien-dictionary/ | ||
* Primary idea: Compare words one by one and make sure they are following the order | ||
* | ||
* Time Complexity: O(n), Space Complexity: O(n) | ||
* | ||
*/ | ||
|
||
class VerifyingAlienDictionary { | ||
func isAlienSorted(_ words: [String], _ order: String) -> Bool { | ||
let charToOrder = Dictionary(uniqueKeysWithValues: order.enumerated().map { ($0.1, $0.0) }) | ||
|
||
for i in 0..<words.count - 1 { | ||
let currentWord = Array(words[i]), nextWord = Array(words[i + 1]) | ||
var j = 0 | ||
|
||
while j < min(currentWord.count, nextWord.count) { | ||
let currentChar = currentWord[j], nextChar = nextWord[j] | ||
|
||
guard currentChar != nextChar else { | ||
j += 1 | ||
continue | ||
} | ||
|
||
if charToOrder[currentChar]! > charToOrder[nextChar]! { | ||
return false | ||
} else { | ||
break | ||
} | ||
} | ||
|
||
// edge case: "apple" vs. "app"; "kuvp" vs. "q" | ||
if j == nextWord.count && currentWord.count > nextWord.count { | ||
return false | ||
} | ||
} | ||
|
||
return true | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters