Skip to content

feat: add swift implementation to lcof2 problem: No.034 #3039

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions lcof2/剑指 Offer II 034. 外星语言是否排序/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,40 @@ function isAlienSorted(words: string[], order: string): boolean {
}
```

#### Swift

```swift
class Solution {
func isAlienSorted(_ words: [String], _ order: String) -> Bool {
var index = [Character: Int]()

for (i, char) in order.enumerated() {
index[char] = i
}

for i in 0..<words.count - 1 {
let w1 = Array(words[i])
let w2 = Array(words[i + 1])
let l1 = w1.count
let l2 = w2.count

for j in 0..<max(l1, l2) {
let i1 = j >= l1 ? -1 : index[w1[j]]!
let i2 = j >= l2 ? -1 : index[w2[j]]!

if i1 > i2 {
return false
}
if i1 < i2 {
break
}
}
}
return true
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
29 changes: 29 additions & 0 deletions lcof2/剑指 Offer II 034. 外星语言是否排序/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
class Solution {
func isAlienSorted(_ words: [String], _ order: String) -> Bool {
var index = [Character: Int]()

for (i, char) in order.enumerated() {
index[char] = i
}

for i in 0..<words.count - 1 {
let w1 = Array(words[i])
let w2 = Array(words[i + 1])
let l1 = w1.count
let l2 = w2.count

for j in 0..<max(l1, l2) {
let i1 = j >= l1 ? -1 : index[w1[j]]!
let i2 = j >= l2 ? -1 : index[w2[j]]!

if i1 > i2 {
return false
}
if i1 < i2 {
break
}
}
}
return true
}
}