|
10 | 10 |
|
11 | 11 | class WordLadder {
|
12 | 12 | func ladderLength(_ beginWord: String, _ endWord: String, _ wordList: [String]) -> Int {
|
13 |
| - guard beginWord.count == endWord.count else { |
14 |
| - return 0 |
15 |
| - } |
16 |
| - |
17 |
| - var queue = [(beginWord, 1)], wordSet = Set<String>(wordList) |
| 13 | + var wordSet = Set(wordList), wordStepQueue = [(beginWord, 1)] |
18 | 14 |
|
19 |
| - while !queue.isEmpty { |
20 |
| - let (word, step) = queue.removeFirst() |
| 15 | + while !wordStepQueue.isEmpty { |
| 16 | + let (currentWord, currentStep) = wordStepQueue.removeFirst() |
21 | 17 |
|
22 |
| - if word == endWord { |
23 |
| - return step |
| 18 | + if currentWord == endWord { |
| 19 | + return currentStep |
24 | 20 | }
|
25 | 21 |
|
26 |
| - // transform word |
27 |
| - for i in 0..<word.count { |
28 |
| - var wordArray = Array(word) |
| 22 | + for word in neighbors(for: currentWord, in: wordSet) { |
29 | 23 |
|
30 |
| - for char in "abcdefghijklmnopqrstuvwxyz" { |
31 |
| - guard char != wordArray[i] else { |
32 |
| - continue |
33 |
| - } |
34 |
| - |
35 |
| - wordArray[i] = char |
36 |
| - let transformedWord = String(wordArray) |
37 |
| - |
38 |
| - guard wordSet.contains(transformedWord) else { |
39 |
| - continue |
40 |
| - } |
41 |
| - |
42 |
| - wordSet.remove(transformedWord) |
43 |
| - queue.append((transformedWord, step + 1)) |
44 |
| - } |
| 24 | + wordStepQueue.append((word, currentStep + 1)) |
| 25 | + wordSet.remove(word) |
45 | 26 | }
|
46 | 27 | }
|
47 | 28 |
|
48 | 29 | return 0
|
49 | 30 | }
|
| 31 | + |
| 32 | + private func neighbors(for word: String, in wordSet: Set<String>) -> [String] { |
| 33 | + var res = [String]() |
| 34 | + |
| 35 | + // change character at every offset of the word |
| 36 | + for i in 0..<word.count { |
| 37 | + var tempWord = Array(word) |
| 38 | + |
| 39 | + for charToReplace in "abcdefghijklmnopqrstuvwxyz" { |
| 40 | + guard charToReplace != tempWord[i] else { |
| 41 | + continue |
| 42 | + } |
| 43 | + |
| 44 | + tempWord[i] = charToReplace |
| 45 | + let tempWordStr = String(tempWord) |
| 46 | + if wordSet.contains(tempWordStr) { |
| 47 | + res.append(tempWordStr) |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return res |
| 53 | + } |
50 | 54 | }
|
0 commit comments