Advertisement
Guest User

Untitled

a guest
Apr 26th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. class Solution {
  2. func ladderLength(_ beginWord: String, _ endWord: String, _ wordList: [String]) -> Int {
  3.  
  4. var wordSet: Set<String> = Set<String>()
  5.  
  6. wordList.forEach {
  7. wordSet.insert($0)
  8. }
  9.  
  10. guard wordSet.contains(endWord) else {
  11. return 0
  12. }
  13.  
  14. var visited: Set<String> = [beginWord]
  15. var queue: Queue<String> = Queue<String>()
  16. queue.enqueue(beginWord)
  17.  
  18. var depth = 1
  19.  
  20. while !queue.isEmpty {
  21. var nextQueue: Queue<String> = Queue<String>()
  22. while let currentWord = queue.dequeue() {
  23. if currentWord == endWord {
  24. return depth
  25. }
  26.  
  27. getNextSate(&nextQueue, currentWord, &visited, wordSet)
  28. }
  29. (queue, nextQueue) = (nextQueue, queue)
  30. depth += 1
  31. }
  32. return 0
  33. }
  34.  
  35. func getNextSate(_ next: inout Queue<String>,_ currentWord: String,_ visited: inout Set<String>,_ dict: Set<String>) {
  36. let alphabetArray = Array("abcdefghijklmnopqrstuvwxyz".characters)
  37. for i in 0 ..< currentWord.characters.count {
  38. var chars = Array(currentWord.characters)
  39. let temp = chars[i]
  40. for j in 0 ..< alphabetArray.count {
  41. if temp == alphabetArray[j] {
  42. continue
  43. }
  44.  
  45. chars[i] = alphabetArray[j]
  46. let newWord = String(chars)
  47. if dict.contains(newWord) && !visited.contains(newWord) {
  48. visited.insert(newWord)
  49. next.enqueue(newWord)
  50. }
  51. }
  52. }
  53. }
  54. }
  55.  
  56. struct Queue<T> {
  57. private var array: [T]
  58. var isEmpty: Bool {
  59. return array.count == 0
  60. }
  61.  
  62. var count: Int {
  63. return array.count
  64. }
  65.  
  66. init() {
  67. array = []
  68. }
  69.  
  70. mutating func enqueue(_ element: T) {
  71. array.append(element)
  72. }
  73.  
  74. mutating func dequeue() -> T? {
  75. if isEmpty { return nil }
  76.  
  77. return array.removeFirst()
  78. }
  79.  
  80. func peek() -> T? {
  81. return array.first
  82. }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement