Advertisement
HXXXXJ

245. Shortest Word Distance III

Jan 30th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.92 KB | None | 0 0
  1.     func shortestWordDistance(_ words: [String], _ word1: String, _ word2: String) -> Int {
  2.         if word1 == word2 {
  3.             return findSame(word1, words)
  4.         }
  5.         var res = Int.max
  6.         var p1 = -1
  7.         var p2 = -1
  8.         for (index, w) in words.enumerated() {
  9.             if w == word1 {
  10.                 p1 = index
  11.                 if p2 != -1 { res = min(res, abs(p1 - p2))}
  12.             }else if w == word2 {
  13.                 p2 = index
  14.                 if p1 != -1 { res = min(res, abs(p1 - p2))}
  15.             }
  16.         }
  17.         return res
  18.     }
  19.     func findSame(_ word: String, _ arr:[String]) -> Int{
  20.         var p = -1
  21.         var res = Int.max
  22.         for (index, w)in arr.enumerated(){
  23.             if w == word{
  24.                 if p != -1 {
  25.                     res = min(res, abs(p - index))
  26.                 }
  27.                 p = index
  28.             }
  29.         }
  30.         return res
  31.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement