Skip to content

Commit a1ce685

Browse files
authored
feat: add swift implementation to lcof2 problem: No.108 (#3621)
1 parent b4a4d5e commit a1ce685

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

lcof2/剑指 Offer II 108. 单词演变/README.md

+37
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,43 @@ func ladderLength(beginWord string, endWord string, wordList []string) int {
204204
}
205205
```
206206

207+
#### Swift
208+
209+
```swift
210+
class Solution {
211+
func ladderLength(_ beginWord: String, _ endWord: String, _ wordList: [String]) -> Int {
212+
var words = Set(wordList)
213+
var queue = [beginWord]
214+
var ans = 1
215+
216+
while !queue.isEmpty {
217+
for _ in 0..<queue.count {
218+
let s = queue.removeFirst()
219+
var chars = Array(s)
220+
for j in 0..<chars.count {
221+
let ch = chars[j]
222+
for k in 0..<26 {
223+
chars[j] = Character(UnicodeScalar(k + 97)!)
224+
let t = String(chars)
225+
if !words.contains(t) {
226+
continue
227+
}
228+
if t == endWord {
229+
return ans + 1
230+
}
231+
queue.append(t)
232+
words.remove(t)
233+
}
234+
chars[j] = ch
235+
}
236+
}
237+
ans += 1
238+
}
239+
return 0
240+
}
241+
}
242+
```
243+
207244
<!-- tabs:end -->
208245

209246
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
func ladderLength(_ beginWord: String, _ endWord: String, _ wordList: [String]) -> Int {
3+
var words = Set(wordList)
4+
var queue = [beginWord]
5+
var ans = 1
6+
7+
while !queue.isEmpty {
8+
for _ in 0..<queue.count {
9+
let s = queue.removeFirst()
10+
var chars = Array(s)
11+
for j in 0..<chars.count {
12+
let ch = chars[j]
13+
for k in 0..<26 {
14+
chars[j] = Character(UnicodeScalar(k + 97)!)
15+
let t = String(chars)
16+
if !words.contains(t) {
17+
continue
18+
}
19+
if t == endWord {
20+
return ans + 1
21+
}
22+
queue.append(t)
23+
words.remove(t)
24+
}
25+
chars[j] = ch
26+
}
27+
}
28+
ans += 1
29+
}
30+
return 0
31+
}
32+
}

0 commit comments

Comments
 (0)